Java Swing - set Jlabel text from another method

Bagshot picture Bagshot · Mar 18, 2012 · Viewed 17.9k times · Source

I'm pretty new to Java and Swing, and I'm using Windowbuilder to play around with a few GUI ideas I have, but I've run into a problem when trying to set the text of a Jlabel.

Windowbuilder has automatically created an instance of the Jlabel, called pathLabel, in the initialize() method like so:

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 570, 393);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel pathLabel = new JLabel("New label");
    pathLabel.setBounds(61, 296, 414, 15);
    frame.getContentPane().add(pathLabel);}

If I use pathLabel.setText("enter text here") from within this initialize() method, then it works fine, but how can I set text from a completely different method? It's not letting me reference it.

I never had this problem in Visual Studio with C#, and was able to set the text of a label from any method I choose. What am I missing?

I hope this makes sense, and I appreciate any help at all. Thanks.

Answer

Gabriel Gonzalez picture Gabriel Gonzalez · Mar 18, 2012

You can create a field for pathLabel in the surrounding class so that all class methods can access it:

class YourClass {
    private JLabel pathLabel;
    private void initialize() {
        ...
        // Note that there is no declaration for pathLabel inside initialize
        //   since it was already declared above, and the above
        //   declaration is a reference shared by all class methods
        pathLabel = new JLabel("New label");
        ...}   
}