White Autumn
White Autumn

Reputation: 35

Java changing the text of JLabel inside another method

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

Upvotes: 2

Views: 203

Answers (1)

wero
wero

Reputation: 32980

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

Upvotes: 1

Related Questions