|
| 1 | +// Java program Program to add a menubar |
| 2 | +// and add menuitems, submenu items and also add |
| 3 | +// ActionListener to menu items |
| 4 | +import java.awt.*; |
| 5 | +import javax.swing.*; |
| 6 | +import java.awt.event.*; |
| 7 | + |
| 8 | +public class menu1 extends JFrame implements ActionListener { |
| 9 | + // menubar |
| 10 | + static JMenuBar mb; |
| 11 | + |
| 12 | + // JMenu |
| 13 | + static JMenu x, x1; |
| 14 | + |
| 15 | + // Menu items |
| 16 | + static JMenuItem m1, m2, m3, s1, s2; |
| 17 | + |
| 18 | + // create a frame |
| 19 | + static JFrame f; |
| 20 | + |
| 21 | + // a label |
| 22 | + static JLabel l; |
| 23 | + |
| 24 | + // main class |
| 25 | + public static void main(String[] args){ |
| 26 | + |
| 27 | + // create an object of the class |
| 28 | + menu1 m = new menu1(); |
| 29 | + |
| 30 | + // create a frame |
| 31 | + f = new JFrame("Menu demo"); |
| 32 | + |
| 33 | + // create a label |
| 34 | + l = new JLabel("no task "); |
| 35 | + |
| 36 | + // create a menubar |
| 37 | + mb = new JMenuBar(); |
| 38 | + |
| 39 | + // create a menu |
| 40 | + x = new JMenu("Menu"); |
| 41 | + x1 = new JMenu("submenu"); |
| 42 | + |
| 43 | + // create menuitems |
| 44 | + m1 = new JMenuItem("MenuItem1"); |
| 45 | + m2 = new JMenuItem("MenuItem2"); |
| 46 | + m3 = new JMenuItem("MenuItem3"); |
| 47 | + s1 = new JMenuItem("SubMenuItem1"); |
| 48 | + s2 = new JMenuItem("SubMenuItem2"); |
| 49 | + |
| 50 | + // add ActionListener to menuItems |
| 51 | + m1.addActionListener(m); |
| 52 | + m2.addActionListener(m); |
| 53 | + m3.addActionListener(m); |
| 54 | + s1.addActionListener(m); |
| 55 | + s2.addActionListener(m); |
| 56 | + |
| 57 | + // add menu items to menu |
| 58 | + x.add(m1); |
| 59 | + x.add(m2); |
| 60 | + x.add(m3); |
| 61 | + x1.add(s1); |
| 62 | + x1.add(s2); |
| 63 | + |
| 64 | + // add submenu |
| 65 | + x.add(x1); |
| 66 | + |
| 67 | + // add menu to menu bar |
| 68 | + mb.add(x); |
| 69 | + |
| 70 | + // add menubar to frame |
| 71 | + f.setJMenuBar(mb); |
| 72 | + |
| 73 | + // add label |
| 74 | + f.add(l); |
| 75 | + |
| 76 | + // set the size of the frame |
| 77 | + f.setSize(500, 500); |
| 78 | + f.setVisible(true); |
| 79 | + } |
| 80 | + public void actionPerformed(ActionEvent e) |
| 81 | + { |
| 82 | + String s = e.getActionCommand(); |
| 83 | + |
| 84 | + // set the label to the menuItem that is selected |
| 85 | + l.setText(s + " selected"); |
| 86 | + } |
| 87 | +} |
0 commit comments