In Java, AWT, repaint-method seems to be ignored in favor of start-method

ⅰ亾dé卋堺 提交于 2019-12-24 06:38:12

问题


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.


回答1:


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.




回答2:


@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.



来源:https://stackoverflow.com/questions/5566994/in-java-awt-repaint-method-seems-to-be-ignored-in-favor-of-start-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!