Forcing Java to refresh the Java Swing GUI - java

Ive coded two Computers to play each other in Reversi, however when they play each other. The board only updates after the game has finished.
From some googling around I know its has something to do the AWT Event Thread, but I still have no idea how to force the JFrame to refresh.
My function works by changing the icons and then calling revalidate and repaint.
Any pointers would be wonderful.

If you start your AI game from an actionPerformed(), it is executed in EDT thread. You should move your logic (and your sleep()'s outside of EDT thread by starting a new Thread to allow Swing to repaint UI properly and post updates to UI as following:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myUI.update(); // repaint(), etc. according to changed states
}
});
Also consider use of javax.swing.SwingWorker, javax.swing.Timer and take a look at Concurrency in Swing.

Sounds like a threading issue - Event Thread is not being given a chance to execute. I would start with some sleep commands in the logic / action threads to give time for the UI to update.
Also, you could have an "updateUI" thread and run that on an invokeAndWait to force it to update the display. Call that after each move has been completed.

If you need to force the application to redraw, you should invoke the repaint() method on the component containing the game board. This should cause Swing to repaint the board.

Related

Repainting JPanel multiple times from an EDT

I have a JPanel with some JButtons on it. When the JButtons are clicked, an event handler is invoked. Within this event handler, I would like the capability of having the JPanel repaint multiple times. There is a lot of processing that occurs in this event handler over the course of several seconds, and I need to be able to update the JPanel to display incremental updates to the user. However, when I call repaint() on the JPanel within the event handler, nothing seems to happen. The JPanel waits to repaint until the event handler has returned.
I have tried using the repaint(long tm) method, but that doesn't seem to help. How do I get this desired behavior of repainting a JPanel multiple times from within an EDT?
Swing is single threaded, so event handlers and painting occur on a single thread (the EDT). If you have computation that takes time and attempt to do so on the EDT, no repainting (or anything else) can be performed. To overcome this, perform the long running tasks on a separate Thread or use a SwingWorker
As most all similar question answers will tell you -- use a SwingWorker to do the long-running task. Push updates to the GUI via the SwingWorker's publish/process method, and when the updates are passed into the GUI, repaint it. This way you avoid stomping on the Swing event thread and avoid freezing your program. Please check out Concurrency in Swing. Also have a look at my code in this answer to a similar question.

Java Wait for Border adjustment to be made in Grid Layout

Hello I have a tile (JLabel) on a Grid Layout Panel
I call this tile.setBorder(BorderFactory.createEmptyBorder()); to update the Border of the tile
then I call a lengthy method, but the image is updated after the lengthy method is done.
I want the Border adjustment to be done and image updated on screen fully before calling the method, how do I do this?
Try with SwingUtilities.invokeLater() to make sure that EDT is initialized properly.
Please have a look at below post to know more about this.
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
Sample code:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// any GUI related code will fall here
tile.setBorder(BorderFactory.createEmptyBorder());
// do not add any lengthy method call here
}
});
For more info read comments below.
but the image is updated after the lengthy method is done.
That is because the long running task is blocking the Event Dispatch Thread and preventing the GUI from repainting itself until the task is finished running. The solution is to use a separate Thread for the task.
Read the section from the Swing tutorial on Concurrency for more information and examples. You may find the SwingWorker more convenients that creating your own Thread.

Java Waiting for repaint() method to finish - Don't know how to implement

I have searched through the many questions saying wait until repaint has finished but I have never found an answer that I could really implement or understand!
I don't want the code to continue when the screen has been repainted!
I have a simple function:
public static void clearScreen()
{
panel.repaint();
}
I can tell you now that this works!
The only problem being that it does not wait to repaint so for example:
public static void blah()
{
drawSomething();
clearScreen();
drawSomething();
}
There is a good chance that both drawings would get clear from the screen. As you might be able to guess I do not want this!
I would just like to mention that all the separate functions work!
Requesting a repaint on a component will add a repaint event to the Event Dispatch Thread which is a separate background thread that will actually call paint() later.
Depending on what you are doing in drawSomething() may happen before or after the event dispatch thread has repainted. The best thing to do is to do all of your work on the event dispatch thread by doing your "draw something" inside a call to SwingUtilities.invokeLater. Which will run your code on the event dispatch thread. All processes on the event dispatch thread are executed in the order they are submitted (usually, some repaint requests are combined etc) so the logical order of calls are preserved.
Learn more about the Event Dispatch Thread in the Oracle Java Tutorial
Swing uses a passive painting system, that is, the screen is not updated on a regular bases, but is painted as is required (or more precisely, when ever the RepaintManager thinks it should be).
You can make requests that UI be updated by calling repaint, buts it's up to the RepaintManager to decide what and when that should occur. The RepaintManager will place a repaint event on the event queue which will be processed by the Event Dispatching Thread at some time in the future.
What this basically means, is that is generally not possible to know when a paint may occur (as painting may happen for all sorts of reasons).
Take a look at Painting in AWT and Swing for more details
You could...
Employee your own buffer, onto which you paint when ever you want, but is the painted to the screen independently. You can use a BufferedImage for this. The problem with this is you're going to have to monitor the changes to the container to ensure that the buffer is the right size
You could...
Implement your own queue, which you add "commands" to, which is then processed by your paint method
The problem with this is ensuring that you lock or copy the queue before processing it

Why doesn't setText work for JLabel component?

I have a JLabel which I want to change momentarily, here is the code I have written to do so:
infoLabel.setText("Added");
try {
TimeUnit.MILLISECONDS.sleep(300);
}
catch(InterruptedException ex)
{
}
infoLabel.setText("Action"); //funny part is when I comment this line it works
My default text for the label is 'Action'
Swing is a single threaded frame work, that means, if you do anything that stops this thread, then it can't respond to any new events, including paint requests.
Basically, TimeUnit.MILLISECONDS.sleep(300) is causing the Event Dispatching Thread to be put to sleep, preventing it from processing any new paint requests (amongst other things).
Instead, you should use a javax.swing.Timer
Take a look at
Concurrency in Swing
How to use Swing Timers
For more details
For example...
infoLabel.setText("Added");
Timer timer = new Timer(300, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
infoLabel.setText("Action");
}
});
timer.setRepeats(false);
timer.start();
Note, 300 milliseconds is a really short time, you might like to start with a value a little larger like 2000, which is 2 seconds ;)
You're sleeping the Swing event thread putting the entire GUI to sleep. Don't do that. Use a Swing Timer instead.
Your application is run on a single thread, so when you sleep the thread, you prevent it from making any GUI updates.
Are you sure you are doing things properly? By doing everything (including sleep) in the GUI thread, it will always be busy and never get back to Java in order to let the GUI be redrawn.
Search for EDT (Event dispatch thread) for more info. Here is one question on the subject: Processing code doesn't work (Threads, draw(), noLoop(), and loop())

Java graphics events not occurring in the order I expect them to

So I'm making a graphical card game. Each card is a JPanel with a button and two images associated with it. I have a flip method, which is the first thing I call in my action listener when a card is clicked on.
public void flip()
{
if(b1.getIcon() == card2) b1.setIcon(card1);
else b1.setIcon(card2);
revalidate();
repaint();
}
However, for some reason the card doesnt flip (meaning the icons don't change) until some point after I call this method. For example, when I put a Thread.sleep after I call flip, I would assume that my program would pause after flip is completed, but it doesnt! It sleeps with the images not yet switched, and only switches them some at point after the sleep time has ended.
This is causing some major problems when I have a human play an AI in this card game, because AI events are happening before cards flip on the screen, even though I am calling flip() before I do any AI code. Can anyone clue me in as to what is going on here?
Repaint is a request to Swing to redraw not a call to redraw. Under the covers repaint() is posting a repaint job onto a queue of events. Along with that repaint job things like mouse moves, mouse clicks, keyboard activites, etc are posted there too. The Swing thread comes by and periodically executes jobs from that queue to redraw the UI, deliver mouse and keyboard events to components, etc. In fact the swing thread delivers these events quite frequently, but it just depends on how much work your UI is doing on that Swing thread. When it's out delivering mouse clicks, keyboard events, and redraws it can't read from that queue. So if your code takes a long time to repsond to any event the ability for swing to respond timely to new events is reduced or all together blocked.
That's why if you execute a blocking service call over the network with the Swing event dispatch thread your UI stops drawing until that call returns. This is why its important to move long running jobs like network calls off the Swing Thread, and use SwingUtilities.invokeLater() when the call comes back so you can update the UI on the Event thread. (invokeLater() does this by posting a job onto the Swing event queue we talked about above).
This is also why it's a terrible idea to call sleep on the Swing event thread. If you put that thread to sleep it can't service events from the queue. And the repaint() you requested isn't going to be done while the Swing thread is sleeping.
First remove your sleep call. Second. Don't write code that depends on painting to finish before executing more logic. Repaint and revalidate are special calls, and Swing will combine requests to repaint/revalidate so it doesn't redraw 10 times in a row (wasting vital cpu time).
Swing can't redraw your panel until you let the thread that called you leave the method it first called you back on. The sooner the thread leaves that method the sooner your repaint() will happen.
You haven't explained why you want the repaint to happen immediately so I can't give you any advice on how to structure your code so you don't care about it. But I'm telling you, you shouldn't care that the repaint hasn't happened yet.
Totally agree with #chubbsondubs. I just wanted to add that if your goal is to have some event happen some time after flip is called, consider using a swing timers. As you are painfully aware, calling Sleep does not have the desired effect. But if instead, you
create a timer for say 1 second
create an action to be performed when the timer fires
start the timer
then you can create the delay that you want without blocking the event dispatch thread.
public void flip()
{
if(b1.getIcon() == card2) b1.setIcon(card1);
else b1.setIcon(card2);
revalidate();
repaint();
javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something interesting
}
});
t.repeats(false);
t.start();
}

Categories

Resources