将文本显示到另一个类的标签 - JFrame
我有一个GUI屏幕,它有一个标签。我现在想用文本设置标签,如下所示(Test
)。但它没有得到更新。我认为在下面的代码中有一个错误,我在try块中重新创建了一个FrameTest的新对象;将文本显示到另一个类的标签 - JFrame
FrameTest frame = new FrameTest();
frame.setVisible(true); //(the full code given below)
的完整代码:注:下面的类是从的JFrame
import java.awt.BorderLayout;
public class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k){
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
}
}
测试类
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
f.writeLabel("FFFFF");
}}
帮助延长,我怎样才能得到文本"FFFFF"
显示的标签?
在你mainScreen()
您创建一个新FrameTest
这是您在日常main
创建一个独特的,所以它实际上改变了文本,无形的框架。试试这个:
private FrameTest frame = this;
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
frame.setVisible(true);
}
});
}
或者干脆:
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
setVisible(true);
}
});
}
添加一个方法你FrameTest
public String readLabel(){
return this.lblLabel.getText();
}
我想要的是编辑'Test'类的标签文本。 –
你用你的代码不会触发你的框架或标签的重绘的方式。 在Swing中,您可以更改许多Gui对象,但只有在请求时才可以在一个批处理中重绘它们。 自动重新绘制时最常见的情况是从事件处理程序返回后。 (例如单击按钮或按键)
不需要这样做,'JLabel'会自动触发它。 – Mordechai
当你改变任何数量的属性时,'JLabel'(就像许多组件)调用'revalidate'和'repaint'。我同意,有时需要微调,但更多的时候则不需要,Swing将自行更新 – MadProgrammer
替换try块;
try {
setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
一切正常!
为什么............? – MadProgrammer
你是什么意思为什么?你有没有看到任何错误? –
'Runnable'没有'setVisible()'方法,你现在正在继承... – Mordechai
更改mainScreen()函数来
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
剩下的代码是相同
这是因为在'mainScreen'函数中,您正在创建另一个JFrame实例并向用户显示。在'Test'类中,您正在创建另一个'JFrame'实例'f'。这两个对象完全不同,对一个对象所做的更改不能在另一个对象中显示。 – sunil
'的setBounds(100,100,450,300);'多少次,我们不得不说的呢?不要设置边界 - 'pack()',然后'setLocationByPlatform(true)'。 –