Search code examples
javaswingintegerjbuttonactionlistener

How can I reach outside int in a button ActionListener?


int a = 0 ;

btnNormal.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e3)
    {
        a = 2;
    }
});

I want to do this, but the eclipse says: Local variable a defined in an enclosing scope must be final or effectively final. If I change to a final int nothing happens. What is the solution? How can I change the int in the actionListener?


Solution

  • You could use an array as a workaround to your problem. Like this:

    int[] a = {0};
    
    btnNormal.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e3)
        {
            a[0] = 2;
        }
    });
    

    Or the AtomicInteger class:

    final AtomicInteger a = new AtomicInteger(0);
    btnNormal.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e3)
        {
            a.set(2);
        }
    });