-1

Is it possible to change a variable from inside of a ActionListener?

I mean somthing like this:

    boolean test = false;

    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            test = true;
        }
    });

I want to change test to true when someone presses the button.

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
Alexander
  • 93
  • 1
  • 2
  • 6

2 Answers2

2

I'm not sure if this helps you but if you are using a action listener I'm guessing you are working with javas swing api. In that case you are maybe extending a class like JFrame or something like that so you could use this:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame {

    private boolean booleanToChange = false;

    private JButton exampleButton;

    public MyFrame() {
        exampleButton = new JButton();
        exampleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                //Access a member in anonymous class
                MyFrame.this.booleanToChange = true;
            }
        });
    }
}

And here the explanation why it has to be final :) hope this helps a bit

Community
  • 1
  • 1
scsere
  • 621
  • 2
  • 15
  • 25
0

This might be what you wanted??

private boolean booly = true; 

private class WinkAction implements ActionListener
{
    public void actionPerformed(ActionEvent e) 
    {

        if (booly){
            booly = false; 
        }else {
            booly = true;
            repaint( );         
        }   
    }
} 
ArK
  • 20,698
  • 67
  • 109
  • 136
Dan Osborne
  • 84
  • 1
  • 3