Artyom M
Artyom M

Reputation: 15

Disable a JButton from a listener that's in a separate class

I'm writing a pretty big class and don't want to post it here. The question is the following, how do I refer to the button that was pressed in the constructor of a different class? Let's say, I want to disable it after some actions in the listener. If the listener were anonymus or were an inner class of the SomeClass, I would just use the name of the variable like this:

button.setEnabled(false);

But how can I do it when my listener is a separate class? Tried using e.getModifiers().setEnabled(false) and e.getSource().setEnabled(false), didn't work.

public class SomeClass extends JPanel {
    private JButton button = new JButton("Button");
    public SomeClass() {
        button.setActionCommand("button");
        button.addActionListener(new ButtonListener());
    }


    public static void main(String[] args) {
        // TODO code application logic here
    }
}
class ButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String src = e.getActionCommand();
        if (src.equals("button")) {
            //some actions here
            //then            
        }        
    }    
}

Upvotes: 0

Views: 365

Answers (1)

alex2410
alex2410

Reputation: 10994

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

It must work)

e.getSource() return component to which this event refers( docs)

Upvotes: 1

Related Questions