将文本显示在另一个类的标签上 - JFrame [英] Display text to a label from another class - JFrame

查看:178
本文介绍了将文本显示在另一个类的标签上 - JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a GUI screen, and it has a label in it. I now want to set the label with a text as i have shown in below (Test). But it's not getting updated. I think there's an error in the follwoing code, where i am recreating a new object of FrameTest in the try block;

FrameTest frame = new FrameTest();
frame.setVisible(true); //(the full code given below)

完整代码:注意:以下类是从 JFrame

The Full Code: Note: the following class is extended from 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 显示在标签上?

Help, how can i get Text "FFFFF" displayed to the label ?

推荐答案

mainScreen()你创建一个新的 FrameTest ,它与你在 main 例程中创建的那个不同,所以它实际上改变了不可见框架的文本。请尝试这样做:

In your mainScreen() you create a new FrameTest that is distinct from the one you create in the main routine, so it's actually changing the text, of the invisible frame. Try this instead:

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

这篇关于将文本显示在另一个类的标签上 - JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆