更改JLabel的文本-初学者 [英] Change the text of a JLabel - Beginner

查看:62
本文介绍了更改JLabel的文本-初学者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码;

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

}

我正在尝试从下面显示的main方法(这是一个单独的类)更改Label的文本;

I am trying to change the Text of the Label from the main method (which is a separate class) shown below;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {

        TestGU g = new TestGU();
        g.mainM();
        g.redefine("New Value");
}
}

1.)当执行main方法时,我希望标签具有文本"New Value",但它仍包含文本New label.一切都没有改变,我该如何纠正呢?

1.) When the main method is executed, i expected the label to have the text "New Value", but it still contains the text New label. Nothing has changed, how can i correct this?

推荐答案

您似乎正在创建TestGU的两个实例,并且您的redefine方法更改了未显示的实例上标签的值.

It looks like you are creating two instances of TestGU and your redefine method changes the value of a label on an instance that isn't displayed.

现在就检查我的理论吧....

Just checking my theory now....


您无需创建第二个实例.您的mainM方法应该是;


You don't need to create the 2nd instance; your mainM method should be;

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

PS-我假设您的初始化方法实际上有这行吗?

PS - I assume that your initialise method actually has this line right?

frame.getContentPane().add(la);

而不是add(null),因为那根本不起作用.

rather than add(null) as that doesn't work at all.

这篇关于更改JLabel的文本-初学者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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