这个问题在这里已经有答案了:
如何在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?
2条答案
按热度按时间tktrz96b1#
从公布的密码来看,
GUI.update(String)
从未像从内部调用的那样调用App.updateText(String)
你从来没有把它作为App.main(String[])
.尝试以下更改
App
:fkvaft9z2#
您应该注意线程,请参阅:swing中的并发
也就是说,试试这样: