简体   繁体   中英

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            
        }        
    }    
}

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

It must work)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM