This code snippet shows how to add a JToolBar component to a form with JButtons.

Listing 1

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