frame shows black screen - java

btnnew.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("Hello");
packetListener.listener();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
I get a black screen when it runs. But when the packetListener.listener(); calls in the constructor it shows.
Can you please explain why this is happening?

Code that is executed from a listener executes on the EDT. I'm guessing that the packetListner.listener() method blocks in which case the GUI will freeze. You should not be blocking the EDT.
Read the section from the Swing tutorial on Concurrency for a full description of this problem and a solution.

I think the packetListener.listener(); method performs some complex operation which blocks your UI.
Better create a thread for listening the packet.
ie,use it like this
try {
System.out.println("Hello");
new Thread(new Runnable() {
public void run() {
packetListener.listener();
}
}).start();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Hope this helps you

Related

Mouse-listener that stops a block from executing when the mouse is released

In Java, I need to integrate a mouse Listener that moves a motor. However here is the catch, there is no stop function. Thereby, the mousepressed should move the motor, while the mouseReleased should stop it, without actually sending a stop command but rather by stopping the mouse pressed block from executing. Any ideas on how this can be implemented? And is it possible to repeat the command under mousePressed as long as the mouse is pressed?
The following code is to illustrate my current program, which uses a stop function, which i would rather avoid.
n2Button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
try {
// moveUp();
session.motion(0, 0, -500);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public void mouseReleased(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
try {
session.stop();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
You rather want to have mouse motion listener
[Example][1] [1]: https://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html
And i also do not see the problem to have session.stop(); only the movement function i guess must be executed in another thread

How to add background music to gamescene in andengine

bg music plays on splash,menu and gamescene when i had put the below code, but i want to make bg music to play only on my gamescene, can you please help me. Thank you.
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException
{
MusicFactory.setAssetBasePath("mfx/");
try {
music = MusicFactory.createMusicFromAsset(mEngine
.getMusicManager(), this, "abcd.wav");
music.setLooping(true);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResourcesManager.prepareManager(mEngine, this, camera, getVertexBufferObjectManager());
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException
{
music.play();
SceneManager.getInstance().createSplashScene(pOnCreateSceneCallback);
}
I usually use music.pause() and music.resume() (because after stop the play does not work any more, I do not know why). When you leave a scene, you can call music.pause(). When you enter a scene, you can call music.resume();

Method not run in java listener actionPerformed

I have a method myFuncs.requestData() that works standalone. It subcribes to listen for data and sets ReadyTxt="TRUE" when the listener has received all the data - which comes in multiple callbacks.
But, when I try to to check DataReady within the actionPerformed method that is attached to a button - it is unset because it appears that myFuncs.requestData() is only processed/run AFTER we come out of actionPerformed.
By "standalone" I mean that if I put no function at ##HERE## then the requestData() works after actionPerformed has completed.
How can I make sure it runs and wait for it to finish at the point ##HERE##?
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
writePaneln("BUTTON PRESSED "+myFuncs.ReadyTxt);
myFuncs.requestData();
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
}
writePaneln("REQUESTED "+myFuncs.ReadyTxt);
##HERE##
}
Threaded version:
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
writePaneln("BUTTON PRESSED "+myFuncs.ReadyTxt);
Thread thread = new Thread() {
public void run(){
myFuncs.requestData();
}
};
thread.start();
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
}
writePaneln("REQUESTED "+myFuncs.ReadyTxt);
##HERE##
}
simplified requestData():
public void requestData() {
DataReady="FALSE"
this.dataSubscription.setListener(this);
}
#Override
public void dataUpdated(List<long> updatedData) {
if (updatedData.size() <= 1 ){
this.dataSubscription.destroy();
writePaneln("In dataUpdated DataReady num: "+Dates.size());
DataReady="TRUE";
return;
}
for (long l: updatedData){
writePaneln(l);
Dates.add(l);
}
}
Answer seems to lie in using TimerTask to time a task for AFTER actioPerformed has completely finished becuase it seems to be on single thread.
http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html

Java - get errors propagated from background thread

I am trying to run a background service as part of my GUI application. I am using an ExecutorService and I am getting a Future back from it. This code shows what I am doing:
play.addActionListener( new ActionListener() {
service.submit(new Runnable(){ .... } }
}
Now, the submission is happening on the GUI thread, which should propagate exceptions to the main thread. Now, I don't want to block the main thread on future.get, but I would rather have some way of checking for the result of the future, so that the exceptions are proapagated to the main thread. Any ideas?
You could use a listener pattern to be notified when the background thread is done. SwingWorker for instance allows for PropertyChangeListeners to listen to the SwingWorker.State state property and you could either do this or roll your own. This is one of my favorite features of a SwingWorker.
An example....
final MySwingWorker mySwingWorker = new MySwingWorker(webPageText);
mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getNewValue().equals(SwingWorker.StateValue.DONE)) {
try {
mySwingWorker.get();
} catch (InterruptedException e) {
e.printStackTrace(); // this needs to be improved
} catch (ExecutionException e) {
e.printStackTrace(); // this needs to be improved
}
}
}
});
mySwingWorker.execute();
You can check Future.isDone() to see if it has finished, or you can have the background task perform the action e.g.
play.addActionListener( new ActionListener() {
service.submit(new Runnable(){
public void run() {
try {
// ....
} catch(Exception e) {
SwingUtils.invokeLater(new Runnable() {
public void run() {
handleException(e);
}
}
}
}
});
You could have an additional thread just to monitor the state of the future:
final Future<?> future = service.submit(...);
new Thread(new Runnable() {
public void run() {
try {
future.get();
} catch (ExecutionException e) {
runOnFutureException(e.getCause());
}
}
}).start();
And somewhere else:
public void runOnFutureException(Exception e) {
System.out.println("future returned an exception");
}

SwingUtilities.invokeLater() displaying just during one frame

I'm using Swing in order to create a little java 2D game. I only try to display an image. Since i'm not on the EDT I'm using SwingUtilities.invokeLater() to do the stuff. When I use it, image is not displayed (in fact it's displayed during few miliseconds and disapear).
When I don't use SwingUtilities.invokeLater() the image is correctly displayed but I need to use invokeLater().
Here's my basic code :
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
final BreizhFrame frame = new BreizhFrame();
File imgFile = new File("src/test/lvl1-800x450.jpg");
System.out.println(String.valueOf(imgFile.exists()));
System.out.println(SwingUtilities.isEventDispatchThread());
Image i;
try {
i = ImageIO.read(imgFile);
frame.getGraphics().drawImage(i, 0, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (InvocationTargetException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any idea ?
Thanks.
That's not how you do it in Java. Yes, you are drawing the image, but after a while the control gets invalidated and it's re-drawn without your image.
This tutorial should help you

Categories

Resources