在我的主Swing框架中,我有这个方法:
public void receiveCommand(String command) {
if (command.equals("enable")) {
Runnable enable = new Runnable() {
public void run() {
button1.setEnabled(true);
button1.revalidate();
button1.repaint();
}
};
SwingUtilities.invokeLater(enable);
}
基本上,我试图通过调用receiveCommand()方法从外部更新GUI(启用按钮 button1 )。
然而,这不起作用,即 button1 仍然被禁用。我在这里做错了什么?
修改: 以下是 button1 :
的声明private javax.swing.JButton button1;
button1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
button1.setEnabled(false);
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button1ActionPerformed(evt);
}
});
button1 和 receiveCommand 方法都在游戏类中:
public class Game extends javax.swing.JFrame
从另一个类调用该方法:
gameUI.receiveCommand("enable"); //gameUI is a Game object
编辑2 :谢谢你的帮助!毕竟,事实证明这是一个错误的参考,所以我所做的只是尝试更新一个尚未设置可见的错误帧的GUI。傻傻的我
答案 0 :(得分:1)
所以无论如何,这都有效。
public class TestInvokeLater {
public static void main(String[] args) {
new TestInvokeLater();
}
public TestInvokeLater() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(12, 12, 12, 12));
final JButton runMe = new JButton("Run me");
runMe.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runMe.setEnabled(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
runMe.setEnabled(true);
}
});
}
}).start();
}
});
setLayout(new GridBagLayout());
add(runMe);
}
}
}