java - 让 Swing 刷新 JLabel 时遇到问题(显然在事件调度线程上)

标签 java swing edt event-dispatch-thread

我有这个 Action 监听器:

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 (MokkiGUI.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();

}

refreshScreen() 似乎不起作用。它们显然在事件调度程序线程上运行,并且所做的更改仅在操作监听器执行结束时才会显示。从 MokkiGUI() 构造函数调用时它工作正常,因为它不在 EDT 上。

最佳答案

您正在阻塞 EDT 线程,因此事件调度循环无法到达重绘事件。要么在 EDT 之外运行并使用 java.awt.EventQueue.invokeLater与 EDT 通信,或使用 javax.swing.Timer (不是 java.util!)在 EDT 上定期运行任务。

关于java - 让 Swing 刷新 JLabel 时遇到问题(显然在事件调度线程上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2678268/

相关文章:

java - 如何为 SFTP (Java) 创建帐户或用户?

java - 我应该在 OnBindViewHolder() 方法中设置 ReyclerView 项目的 OnClickListener 吗?

Java - 如果之后定义了 actionPerformed,JButton 文本就会消失

java - SwingUtilities InvokeLater-什么被认为是不好的做法?

java - 在 Swing 中,您可以将事件发布到 EDT 事件队列的顶部吗?

java - @SingleValueResult 做什么?

java - JSF的使用示例

java - 如何更改 JComboBox 下拉列表的宽度?

java - 防止多个用户执行相同的操作

java - TreeSet 表现得很奇怪