How to add action listener that listens to multiple buttons

后端 未结 11 1105
温柔的废话
温柔的废话 2020-11-27 04:25

I\'m trying to figure out what i am doing wrong with action listeners. I\'m following multiple tutorials and yet netbeans and eclipse are giving me errors when im trying to

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 05:01

    I'm amazed that nobody has mentioned using an action command. This is a pretty standard way of associating sources and listeners. Its really useful if;

    • you have multiple event sources that need to do the same thing (eg if you want the use to be able to press the enter key on a text field as an alternative to clicking a button next to it)
    • you don't have a ref to the component generating the event

    see;

    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;    
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    
    public class DontExtendJFrame implements ActionListener {
    
      private enum Actions {
        HELLO,
        GOODBYE
      }
    
      public static void main(String[] args) {
    
        DontExtendJFrame instance = new DontExtendJFrame();
    
        JFrame frame = new JFrame("Test");
        frame.setLayout(new FlowLayout());
        frame.setSize(200, 100);
    
        JButton hello = new JButton("Hello");
        hello.setActionCommand(Actions.HELLO.name());
        hello.addActionListener(instance);
        frame.add(hello);
    
        JButton goodbye = new JButton("Goodbye");
        goodbye.setActionCommand(Actions.GOODBYE.name());
        goodbye.addActionListener(instance);
        frame.add(goodbye);
    
        frame.setVisible(true);
      }
    
      @Override
      public void actionPerformed(ActionEvent evt) {
        if (evt.getActionCommand() == Actions.HELLO.name()) {
          JOptionPane.showMessageDialog(null, "Hello");
        } else if (evt.getActionCommand() == Actions.GOODBYE.name()) {
          JOptionPane.showMessageDialog(null, "Goodbye");
        }
      }
    }
    

提交回复
热议问题