Posted By

syedhussim on 07/05/17


Tagged

actionListener JButton


Versions (?)

Multiple JButtons With A Single ActionListener


 / Published in: Java
 

URL: http://www.snippetcentral.net/java/multiple-jbuttons-with-a-single-actionlistener.html

This code snippet shows how to handle multiple JButtons with a single ActionListener.

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

Report this snippet  

You need to login to post a comment.