Java 从另一个类设置gui内容
我希望能够从另一个类更改某些Java 从另一个类设置gui内容,java,swing,Java,Swing,我希望能够从另一个类更改某些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
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);
}
}
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);
}
}
但是,此解决方案不起作用,GUI.update(String)
在GUI
类中调用时工作正常。
我检查了Paul在中提出的解决方案:
但我不明白。
那么,我如何从另一个类调用
GUI
上的方法来更改UI呢?从发布的代码判断,GUI.update(String)
从来不会被调用,因为它是从App.updateText(String)
中调用的,而你从来不会作为App.main(String[])
的一部分调用它
尝试对应用程序进行以下更改:
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);
}
}
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);
}
}
您应该注意线程,请参阅:
也就是说,试着这样做:
public void update(final String s) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
this.label.setText(s);
}
});
}
请提供详细信息,以便我们更容易理解您的问题。这里发布的代码既没有告诉我们如何构建GUI,也没有告诉我们如何调用方法updatext
。感谢您的回复,Janus,我们的想法是从任何类调用App.updatext(),因为App是保存窗口(GUI实例)的地方。假设我们在GUI=>result的实例化之后调用App.updateText(“某些字符串”):不幸的是,windowSwing组件中没有任何更改,都有repaint()、revalidate()和doLayout()方法。其中一个应该能够重新绘制任何你想要的部分。但是,doLayout不是你应该负责的事情,那是布局引擎的责任。谢谢Janus,我尝试过这个,不幸的是,窗口上仍然没有任何变化。事实上,确实调用并执行了GUI.update(),但没有显示GUI上的更改。