gpt4 book ai didi

Java 事件队列 : how to update component in JFrame

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:10 24 4
gpt4 key购买 nike

我听说在编写 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 稍后。

请告诉我这个错误以及如何解决这个问题。

谢谢:)

最佳答案

通过将您的 SwingExample 实例作为一个字段,您可以在内部类中引用它而无需 final

public class SwingExample {

private JLabel lblLabel;
private static SwingExample instance;

SwingExample() {
// code omitted
}

public void setLabel() {
lblLabel.setText("Bye Bye !!!");
}

public static void main(String[] args) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
instance = new SwingExample();
}
});

// ...

EventQueue.invokeLater(new Runnable() {
public void run() {
instance.setLabel();
}
});
}
}

关于Java 事件队列 : how to update component in JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12104833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com