我的代码;
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图从主方法(这是一个单独的类)更改标签的文本,如下所示;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
TestGU g = new TestGU();
g.mainM();
g.redefine("New Value");
}
}
Run Code Online (Sandbox Code Playgroud)
1.)当执行main方法时,我希望标签有文本"New Value",但它仍然包含文本New label.什么都没有改变,我怎么能纠正这个?
看起来您正在创建两个实例,TestGU并且您的redefine方法会更改未显示的实例上的标签值.
现在就检查一下我的理论......
编辑:
您不需要创建第二个实例; 你的mainM方法应该是;
public void mainM() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
PS - 我认为你的初始化方法实际上有这条线吗?
frame.getContentPane().add(la);
Run Code Online (Sandbox Code Playgroud)
而不是add(null)那根本不起作用.