1

我正在构建一个棋盘游戏小程序,处理用户输入大致如下所示:

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();
    }
}

在人工输入之后,计算机选择一个移动并像这个方法一样调用 repaint() 和 start()。
但是屏幕似乎只有在计算机移动之后才会更新,所以在调用 start() 之后。这怎么会发生,因为 repaint() 在 start() 之前被调用?

我怀疑这可能是因为 repaint() 启动了一个新线程(是吗?),但它为什么要等待 start()?

当然,如果需要,我可以提供更多代码。

4

2 回答 2

5

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.

于 2011-04-06T14:03:58.120 回答
1

@DJClayworth 已经解释了为什么您的应用程序的行为如此,但如果您正在使用 aJComponent并且您在自己的事件处理期间绝对需要重新绘制,您可以使用其中一种JComponent.paintImmediately()方法。但是,您可能应该先花一些时间来决定是否可以重构代码以使start()功能在事件分派线程之外发生。

于 2011-04-06T14:20:46.847 回答