Alexander Alexander - 2 years ago 143
Java Question

Change Variable from the inside of a ActionListener

Is it possible to change a Variable from the "inside" of a ActionListener.
I mean somthing like this:

boolean test = false;

white.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

test = true;


I want to change white to True when someone presses the button.

And sorry for my bad Grammar :(

Answer Source

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() {
            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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download