This code snippet shows how to handle multiple JButtons with a single ActionListener. If your form consists of a few buttons, you can use one ActionListener to handle the operations of these buttons. The getActionCommand() can be used to determine which button was pressed.

Listing 1

  1. 1import  javax.swing.JFrame;
  2. 2import  javax.swing.JPanel;
  3. 3import  javax.swing.JButton;
  4. 4import  java.awt.event.ActionListener;
  5. 5import  java.awt.event.ActionEvent;
  6. 6
  7. 7class  Main  implements  ActionListener{
  8. 8        
  9. 9        public  static  void  main(String  args[]){
  10. 10                Main  main  =  new  Main();
  11. 11        }
  12. 12        
  13. 13        public  Main(){
  14. 14                JFrame  frame  =  new  JFrame();
  15. 15                JPanel  panel  =  new  JPanel();
  16. 16                
  17. 17                JButton  button1  =  new  JButton();
  18. 18                button1.setText("Button 1");
  19. 19                button1.addActionListener(this);
  20. 20                
  21. 21                JButton  button2  =  new  JButton();
  22. 22                button2.setText("Button 2");
  23. 23                button2.addActionListener(this);
  24. 24                
  25. 25                panel.add(button1);
  26. 26                panel.add(button2);
  27. 27                
  28. 28                frame.getContentPane().add(panel);
  29. 29                
  30. 30                frame.setSize(200,200);
  31. 31                frame.setVisible(true);
  32. 32        }
  33. 33        
  34. 34        public  void  actionPerformed(ActionEvent  e){
  35. 35                switch(e.getActionCommand()){
  36. 36                        case  "Button 1":
  37. 37                                System.out.println("You clicked Button 1");
  38. 38                                break;
  39. 39                        case  "Button 2":
  40. 40                                System.out.println("You clicked Button 2");
  41. 41                                break;
  42. 42                }
  43. 43        }
  44. 44}