Java changing the text of JLabel inside another method

时光怂恿深爱的人放手 提交于 2021-01-27 17:35:36

问题


I want to change the text of a JLabel outside of the method I created it in.

I've looked through the other pages on the same topic but I still cannot get it to work. Perhaps I am lacking knowledge of Java to solve this by myself. Would you please help me?

package autumn;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {

    private JFrame frame;

    JLabel TestLabel;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main window = new Main();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public Main() {
        initialize();
        setText();
    }
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JLabel TestLabel = new JLabel("");
        TestLabel.setBounds(0, 0, 46, 14);
        frame.getContentPane().add(TestLabel);
    }
    void setText() {
        TestLabel.setText("Works!");
    }
}

回答1:


You have a class field JLabel TestLabel.

But in the initializemethod you shadow this field by using a local variable with the same name:

JLabel TestLabel = new JLabel("");

so the class field is not initialized and the later call to setText fails.

Therefore simply write:

TestLabel = new JLabel("");  // assigns to Main.TestLabel


来源:https://stackoverflow.com/questions/33474297/java-changing-the-text-of-jlabel-inside-another-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!