My code;
package com.test;
import java.awt.EventQueue;
public class TestGU {
private JFrame frame;
private JLabel la;
/**
* Launch the application.
*/
public void mainM() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestGU window = new TestGU();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void redefine(String text){
la.setText(text);
frame.repaint();
}
/**
* Create the application.
*/
public TestGU() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
la = new JLabel("New label");
frame.getContentPane().add(null);
}
}
我正在尝试从如下所示的主方法(这是一个单独的类)更改标签的文本;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
TestGU g = new TestGU();
g.mainM();
g.redefine("New Value");
}
}
1.) 当执行 main 方法时,我期望标签具有文本“New Value”,但它仍然包含文本New label
。什么都没有改变,我该如何纠正这个问题?
看起来您正在创建两个实例TestGU
和你的redefine
方法更改未显示的实例上的标签值。
现在只是检查我的理论......
Edit:
您不需要创建第二个实例;你的 mainM 方法应该是;
public void mainM() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
PS - 我假设你的初始化方法实际上有这一行,对吗?
frame.getContentPane().add(la);
而不是add(null)
因为那根本不起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)