Bagshot
Bagshot

Reputation: 57

Java Swing - set Jlabel text from another method

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.

Upvotes: 2

Views: 18571

Answers (2)

mohit jain
mohit jain

Reputation: 407

You can put pathLabel as a instance variable in your class and access it across all the methods in the class.

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

   pathLabel = new JLabel("New label");
   pathLabel.setBounds(61, 296, 414, 15);
   frame.getContentPane().add(pathLabel);
}
void func(){
   pathLabel.setText("enter text here");
}

Upvotes: 2

Gabriella Gonzalez
Gabriella Gonzalez

Reputation: 35089

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

Upvotes: 2

Related Questions