将文本显示在另一个类的标签上 – JFrame

我有一个GUI屏幕,它有一个标签。 我现在想用标签设置标签,如下所示( Test )。 但它没有得到更新。 我认为在下面的代码中有一个错误,我在try块中重新创建一个FrameTest的新对象;

 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()您创建一个与您在main例程中创建的FrameTest不同的新FrameTest ,因此它实际上正在更改不可见帧的文本。 试试这个:

 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(); } 

将mainScreen()函数更改为

 public void mainScreen() { EventQueue.invokeLater(new Runnable() { public void run() { try { setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } 

剩下的代码是一样的

您使用代码的方式不会触发您的框架或标签的重绘。 在Swing中,您可以更改许多Gui对象,但只有在请求时才会在一个批处理中重绘它们。 重新绘制自动发生的最常见情况是从事件处理程序返回后。 (例如按下按钮或按键)

替换try块;

  try { setVisible(true); } catch (Exception e) { e.printStackTrace(); } 

一切正常!