This code snippet shows how to add an action listener to a JButton.

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{
  8. 8        
  9. 9        public  static  void  main(String  args[]){
  10. 10                
  11. 11                JFrame  frame  =  new  JFrame();
  12. 12                JPanel  panel  =  new  JPanel();
  13. 13                
  14. 14                JButton  button  =  new  JButton();
  15. 15                button.setText("Click me");
  16. 16                button.addActionListener(new  ActionListener(){
  17. 17                        public  void  actionPerformed(ActionEvent  e){
  18. 18                                System.out.println("Hello World");        
  19. 19                        }
  20. 20                });
  21. 21                
  22. 22                panel.add(button);
  23. 23                
  24. 24                frame.getContentPane().add(panel);
  25. 25                
  26. 26                frame.setSize(200,200);
  27. 27                frame.setVisible(true);
  28. 28        }
  29. 29}

An alternative to the above code is to have the Main class implement an ActionListener as show in Listing 2 below.

Listing 2

  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  button  =  new  JButton();
  18. 18                button.setText("Click me");
  19. 19                button.addActionListener(this);
  20. 20                
  21. 21                panel.add(button);
  22. 22                
  23. 23                frame.getContentPane().add(panel);
  24. 24                
  25. 25                frame.setSize(200,200);
  26. 26                frame.setVisible(true);
  27. 27        }
  28. 28        
  29. 29        public  void  actionPerformed(ActionEvent  e){
  30. 30                System.out.println("Hello World");        
  31. 31        }
  32. 32}

If a class implements an ActionListener, it must then implement the actionPerformed method as a class method.