Search code examples
javaswingjbuttonactionlistenerfinal

Change value of a local variable that needs to be declared final


I have been trying to change the position of my JButton in the action listener. However, when I compiled my code Local variable is accessed from within inner class: needs to be declared final error was displayed. Therefore, I declared my location variable as final. The problem is that I need to change the value of my location variable and that is not possible as long as its final. How do I solve this?

Code:

final int location =100;

JFrame f = new JFrame();
final JButton b1 = new JButton("character");

f.setVisible(true);
f.setSize(500,500);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setLayout( new FlowLayout());

f.add(b1);

b1.addActionListener(new ActionListener() {     
  public void actionPerformed(ActionEvent e) {
     b1.setLocation(location,100);
     location += 10; // cannot assign a value to final variable location
  }
});

Solution

  • You can do it in two ways,

    1) Implement ActionListener to your parent class then in

    ParentClass implements ActionListener 
    {
    int location =100;
     //...Codes codes..
     public void actionPerformed(ActionEvent e) {
     //perform null check 
      if (b1==(JButton)e.getSource()){
       b1.setLocation(location,100);
        location += 10;
    
        }
      }
    }
    

    2) Call static variables from inner class, (remember: This is a bad method of programming)

     //static class to store variables
      Class StaticVariables{
      static int location=100;
     }
    
    
    
    class ParentClass{
    
        //..Codes Codes..
    
        b1.addActionListener(new ActionListener() {
        //Calling Static class varible
        int localLocationVariable=StaticVariables.location;
        b1.setLocation(localLocationVariable,100);
        localLocationVariable+= 10;
        StaticVariables.location=localLocationVariable;
        }
    

    Hopes this may help you.