Reference to variables from anonymous classes in Java

I am writing a listonclick listner, and I want to be able to refer to this button so that I can change its properties. That is, make it disabled?

I get thismessage:

Cannot reference undefined variable confirmButton inside inner class defined in another way

        confirmButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            confirmButton.setEnabled(false);    
        }



    }); 
+3
source share
4 answers

This is because you are probably trying to access this button from an anonymous class that you use this way:

button.addActionListener(
  new MyListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      //do your things on button }
    }
  }
);

, Java , , , . , final, , , .

, ActionEvent actionPerformed:

((JButton)e.getSource()).setEnabled(false)

ActionListener - static final.. , .

+3

getSource; , . final ,

public class ComponentRelevantOnClickListener implements View.OnClickListener {

  private JComponent component;

  public ComponentRelevantOnClickListener(JComponent component) {
    this.component = component;
  }
}

// then, in your code...

confirmButton.setOnClickListener(new ComponentRelevantOnClickListener(confirmButton) {

    public void onClick(View view) {
        component.setEnabled(false);    
    }
});

, ( , ComponentRelevantOnClickListener "DisableOnClickListneer", ), .

+1

vars, , final Java. .

0

Anonymous inner classes can only access variables from the outer scope, if they are final. Assuming you assign only confirmButtononce, I suggest just marking it as final.

final JButton confirmButton = new JButton();
0
source

Source: https://habr.com/ru/post/1751891/


All Articles