Reputation: 7318
I'm building an applet of a board game, and handling user input roughly looks like this:
public void mousePressed(MouseEvent event) {
int row = event.getX() / (getSize().width / 8) ;
int column = event.getY() / (getSize().height / 8) ;
if(possibleMove(column, row) {
makeMove(column,row,whosTurn);
repaint();
start();
}
}
After a human input, the computer chooses a move and calls repaint() and start() like this method does.
But the screen seems to update only after the computer has made a move, so after start() is called. How can this happen, since repaint() is called before start()?
I have a suspicion this might be because repaint() launches a new thread (does it?), but why would it wait for start()?
I could provide more code if necessary, of course.
Upvotes: 1
Views: 1554
Reputation: 26876
The repaint() call does not do the repaint - it schedules a repaint to be done. The actual repaint is carried out later by the event thread after any current and already scheduled events have been finished (it may happen even later than that for other reasons not relevant here). The start() method is called immediately after the scheduling is done, as part of responding to the current event. So yes, the actual paint will always take place after start() is called.
See the description of repaint() and the description of the paint mechanism for more details.
In general calling start() like this is probably bad. While start() is being called the UI cannot respond to anything (such as the game window being resized or uncovered), and unless start() is a very short action this will result in the UI seeming unresponsive.
Upvotes: 5
Reputation: 5694
@DJClayworth has already explained why your app behaves as it does, but if you're working with a JComponent
and you absolutely need repainting to happen during your own event handling, you can use one of the JComponent.paintImmediately()
methods. However, you should probably spend some time first deciding whether you can refactor your code to have the start()
functionality happen outside of the event dispatch thread.
Upvotes: 1