2

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.

Bagshot
  • 57
  • 1
  • 2
  • 7
  • 3
    Another reason not to use a code-generator to build Swing code. Consider going through the Swing tutorials to learn to code this by hand. – Hovercraft Full Of Eels Mar 18 '12 at 19:20
  • `setBounds(..)` No! Learn how to use layouts (with padding) & borders! – Andrew Thompson Mar 18 '12 at 19:23
  • 2
    *"I never had this problem in Visual Studio with C#"* Writing things like that is not a great way to encourage people to answer. Different languages have different strengths weaknesses, & uses. Java is an x-plat language that requires layouts to size and align components reliably. Using layouts is not as simple as dragging and dropping components to a known/fixed location. – Andrew Thompson Mar 18 '12 at 19:30

2 Answers2

2

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");
        ...}   
}
Gabriella Gonzalez
  • 34,863
  • 3
  • 77
  • 135
2

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");
}
mohit jain
  • 397
  • 1
  • 3
  • 14