开发者

Trouble getting Swing to refresh JLabel (apparently on event dispatch thread)

I have this action listener:

this.newGameButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent a) {
    MokkiGUI.this.game = newGameQuery();
    MokkiGUI.this.AI = new AIPlayer(MokkiGUI.this.game.getBoard());
    MokkiGUI.this.boardLabel.setText("");
    MokkiGUI.this.boardLabel.repaint();
    refreshScreen();
    JOptionPane.showMessageDialog(null, "Starting new game", "New game", JOptionPane.PLAIN_MESSAGE);
    if (MokkiG开发者_如何学PythonUI.this.game.getAIIndicator() % 2 == 1) {
      while (makeAIMove()) {
        MokkiGUI.this.refreshScreen();
      }
      MokkiGUI.this.refreshScreen();
    }
  }
});

public void refreshScreen() {
if (javax.swing.SwingUtilities.isEventDispatchThread()) {
  System.out.println("Is");
} else {
  System.out.println("Not");
}
MokkiGUI.this.boardLabel.setText(MokkiTest.printBoard(MokkiGUI.this.game.getBoard()));
MokkiGUI.this.boardLabel.repaint();
MokkiGUI.this.data.setText("X: " + MokkiGUI.this.game.getPlayer1name() + "\n Score: "
    + MokkiGUI.this.game.getPlayer1score() + "\n\n" + "O: " + MokkiGUI.this.game.getPlayer2name() + "\n Score: "
    + MokkiGUI.this.game.getPlayer2score());
MokkiGUI.this.data.repaint();
if (!MokkiGUI.this.game.redoable()) {
  MokkiGUI.this.forwardButton.setEnabled(false);
  MokkiGUI.this.allForwardButton.setEnabled(false);
} else {
  MokkiGUI.this.forwardButton.setEnabled(true);
  MokkiGUI.this.allForwardButton.setEnabled(true);
}
if (!MokkiGUI.this.game.undoable()) {
  MokkiGUI.this.backButton.setEnabled(false);
  MokkiGUI.this.allBackButton.setEnabled(false);
} else {
  MokkiGUI.this.backButton.setEnabled(true);
  MokkiGUI.this.allBackButton.setEnabled(true);
}
MokkiGUI.this.buttonPanel.repaint();

}

The refreshScreen()s don't seem to work. They are apprently running on the Event Dispatcher thread and the changes made only show up when the action listener's execution is over. It works fine when called from the MokkiGUI() constructor, as it is not on the EDT.


You are blocking the EDT thread, so it event dispatch loop can't get to the repaint events. Either run outside of the EDT and use java.awt.EventQueue.invokeLater to communicate with the EDT, or use javax.swing.Timer (not java.util!) to regularly run tasks on the EDT.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜