1

Below is my codes:

JLabel label1 = new JLabel("testcontent");
label1.setBounds(131, 57, 205, 74);

frame.getContentPane().add(label1);

JButton btn1 = new JButton("run");
btn1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

    }
});

btn1.setBounds(169, 206, 117, 25);
frame.getContentPane().add(btn1);

When I try to refer the label1 in the actionPerformed, eclipse cannot find the label1. Any one could tell me what's wrong?

MirroredFate
  • 12,396
  • 14
  • 68
  • 100
wsndy
  • 51
  • 1
  • 4

2 Answers2

6

label1 is not available in the scope of the ActionListener. Either declare it as final or make it a class instance variable

final JLabel label1 = new JLabel("testcontent");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • You're not using `final` as a design decision, you're using as a workaround- a completely unnecessary workaround, at that. It's poor programming. – MirroredFate Sep 11 '13 at 15:57
1

You can get around using final by doing what is described in this answer.

Basically, you pass in the label through an init method that you call immediately after creating an anonymous object. In your case, it would look something like this:

btn1.addActionListener(new ActionListener() {
    private JLabel myLabel;
    private ActionListener init(JLabel var){
        myLabel = var;
        return this;
    }
    public void actionPerformed(ActionEvent e) {

    }
}.init(myVariable));

The reference myLabel is then accessible within btn1's actionPerformedmethod.

Community
  • 1
  • 1
MirroredFate
  • 12,396
  • 14
  • 68
  • 100