Java 在另一个方法中更改 JLabel 的文本

Java changing the text of JLabel inside another method

我想在创建它的方法之外更改 JLabel 的文本。

我已经浏览了同一主题的其他页面,但仍然无法正常工作。也许我缺乏 Java 的知识来自己解决这个问题。 你能帮帮我吗?

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

您有一个 class 字段 JLabel TestLabel

但是在 initialize 方法中,您通过使用同名的局部变量隐藏此字段:

JLabel TestLabel = new JLabel("");

因此 class 字段未初始化,稍后对 setText 的调用失败。

因此简单地写:

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