Search code examples
javajlabel

Why can't I access a JLabel outside of the constructor?


So I created a JLabel in the constructor of my main class, then, I have a separate method in the class to update it (updateLabel()). But can't access the Label from in the update method. How can I access it from inside the method? Thanks

public Difficulty(){
    JLabel lblNewLabel = new JLabel((comboBox_9.getSelectedItem().toString()));
    lblNewLabel.setBounds(300, 70, 46, 23);
    contentPane.add(lblNewLabel);
}

public void updateLabel(Skill skill){

}

In the update Label method I want to say lblNewLabel.setText(skill.toString())

But I can't access the label.


Solution

  • You need to consider variable scope: Java Tutorials - Declaring Member Variables

    If you declare an object within the scope of your constructor then it won't be accessible elsewhere, for example your updateLabel() method.

    Try declaring your JLabel as field, for instance:

    private JLabel label;
    
    public JLabelContainer() {
       label = new JLabel();
    }
    
    public void updateLabel(String text){
      label.setText(text);
    }
    

    Here, the label is declared at the field level, instantiated in the constructor and then accessed in the updateLabel(..) method.