我读到过,在编写 Java Swing 时,我们应该将这些组件放入 Java Event Queue,因为 Java Swing 线程不是线程安全的。
但是,当我使用 时Event Queue
,我不知道如何更新组件属性(例如:为标签设置文本或更改某些内容..)。这是我的代码:
public class SwingExample {
private JLabel lblLabel;
SwingExample(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
lblLabel = new JLabel("Hello, world!", JLabel.CENTER);
frame.getContentPane().add(lblLabel); // adds to CENTER
frame.setSize(200, 150);
frame.setVisible(true);
}
public void setLabel(){
lblLabel.setText("Bye Bye !!!");
}
public static void main(String[] args) throws Exception
{
SwingExample example = null;
EventQueue.invokeLater(new Runnable()
{
public void run()
{
example = new SwingExample(); // ERROR : Cannot refer to non-final variable inside an inner class defined in different method
}
});
// sometime in the futures, i want to update label, so i will call this method...
example.setLabel();
}
}
我知道,如果我写SwingExample example = new SwingExample();
了错误就不会再次出现,但是如果我使用它,我以后无法处理example.setLabel
。
请告诉我这个错误以及如何解决这个问题。
谢谢 :)