【发布时间】:2012-11-16 11:21:55
【问题描述】:
我的代码;
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 label。什么都没有改变,我该如何纠正?
【问题讨论】:
-
frame.getContentPane().add(null);无法编译。那是你的真实代码吗?此外,您的代码运行initialize两次,因此有 2 个 TestGU 对象。 -
JLabel 也永远不会添加到框架中。
-
null 表示绝对布局对吗?
-
"null 表示绝对布局对吗?" 错误。这意味着在内容窗格中不添加任何内容。顺便说一句 - 使用布局!
-
如何添加绝对布局?