从另一个类设置gui内容

k5hmc34c  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(191)

这个问题在这里已经有答案了

如何在java中刷新gui(3个答案)
11个月前关门了。
我想能够改变一些 JLabel 来自其他类的对象。我有一个 GUI 包含所有gui对象的类( JFrame , JPanel 等)。假设我只有一个 JLabel :

public class GUI {
    private JLabel label;

    public GUI() {
        initialize();//initializes all objects
    }

    public void update(String s) {
        this.label.setText(s);
    }
}
``` `GUI` 具有公共职能 `update(String)` 我希望从另一个班级打电话。
我的主课叫 `App` :

public class App {
private static GUI window;

public static void main( String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                window = new GUI();
                App.updateTxt("some string");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     });
}

public  static void updateTxt(String s) {
    window.update(s);
}

}

但是,这个解决方案不起作用, `GUI.update(String)` 在内部调用时工作正常 `GUI` 班级。我检查了paul在中提出的解决方案:从另一个类访问gui组件,但我不理解它。那么我如何调用 `GUI` 从另一个类更改ui?
tktrz96b

tktrz96b1#

从公布的密码来看, GUI.update(String) 从未像从内部调用的那样调用 App.updateText(String) 你从来没有把它作为 App.main(String[]) .
尝试以下更改 App :

public class App {
    private static GUI window;

    public static void main( String[] args) throws InterruptedException {
        window = new GUI();
        Thread.sleep(1000); // Pause for 1 second.       
        updateText("Hello, world!"); // Update the label with new text.
    }

    public  static void updateTxt(String s) {
        window.update(s);
    }
}
fkvaft9z

fkvaft9z2#

您应该注意线程,请参阅:swing中的并发
也就是说,试试这样:

public void update(final String s) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            this.label.setText(s);
        }
    });
}

相关问题