JMenuBar - Part 2

The Event Listeners for the MenuBar are no different than those we have used before.

JMenuBar, JMenu, JMenuItem and JRadioButtonMenuItem all use the ActionListener.
JCheckBoxMenuItem uses the ItemListener.

All we do is add a listener to each, then catch them with event catcher methods below.

Although I love you guys, let's not add a listener to every single item in the MenuBar. In this example I've cut away a good chunk of the MenuBar and have only one instance of each object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;

// Class implements three different types of listener.
public class MenuBarExample_Extended implements  ActionListener, ItemListener{

    JTextArea whitebox;
    JCheckBoxMenuItem cake, sorbet;
    
    public Container createContentPane()
    {
        whitebox = new JTextArea();
        whitebox.setEditable(false);
        whitebox.setLineWrap(true);
        whitebox.setWrapStyleWord(true);
        whitebox.setMinimumSize(new Dimension(300, 200));
        whitebox.setPreferredSize(new Dimension(300, 200));
        whitebox.setMaximumSize(new Dimension(300, 200));

        JPanel totalGUI = new JPanel();
        totalGUI.add(whitebox);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    public JMenuBar createMenuBar()
    {
        //Create the menu bar.
        JMenuBar menuBar = new JMenuBar();

        //Add a JMenu
        JMenu starter = new JMenu("Starters");
        menuBar.add(starter);

        // Now we want to fill the menu.
        // This has every type of widget in the MenuBar
        // and has Event Listeners attached to each.
          
        JMenuItem soup = new JMenuItem("Soup");
        soup.addActionListener(this);

        JMenu steak = new JMenu("Steak");
           
        JMenuItem rare = new JMenuItem("Rare");
        rare.addActionListener(this);
        JMenuItem welldone = new JMenuItem("Well Done");
        welldone.addActionListener(this);
        steak.add(rare);
        steak.add(welldone);

        JRadioButtonMenuItem chips = new JRadioButtonMenuItem("Chips");
        chips.addActionListener(this);
        JRadioButtonMenuItem bp = new JRadioButtonMenuItem("Baked Potato");
        bp.addActionListener(this);

        ButtonGroup sides = new ButtonGroup();
        sides.add(chips);
        sides.add(bp);

        cake = new JCheckBoxMenuItem("Cake");
        cake.addItemListener(this);
        sorbet = new JCheckBoxMenuItem("Sorbet");
        sorbet.addItemListener(this);

        starter.add(soup);
        starter.addSeparator();
        starter.add(steak);
        starter.addSeparator();
        starter.add(chips);
        starter.add(bp);
        starter.addSeparator();
        starter.add(cake);
        starter.add(sorbet);

        return menuBar;
    }

    // Deals with the Action Events.
    public void actionPerformed(ActionEvent e)
    {
        whitebox.append(e.getActionCommand() + " Selected \n");
    }

    // Deals with the Item Events.
    public void itemStateChanged(ItemEvent e)
    {     
        if(e.getSource() == cake)
        {
            whitebox.append("Cake Clicked\n");
        }
        else if(e.getSource() == sorbet)
        {
            whitebox.append("Sorbet Clicked\n");
        }
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JMenuBar [=]");

        //Create and set up the ContentPane and MenuBar
        MenuBarExample_Extended demo = new MenuBarExample_Extended();
        
        frame.setContentPane(demo.createContentPane());
        frame.setJMenuBar(demo.createMenuBar());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
Picture of MenuBar

The class needs to implement both ActionListeners and ItemListeners.
8
public class MenuBarExample_Extended implements  ActionListener, ItemListener{
The ActionListeners and ItemListeners are just added like normal.
50
51
        JMenuItem welldone = new JMenuItem("Well Done");
        welldone.addActionListener(this);
64
65
        cake = new JCheckBoxMenuItem("Cake");
        cake.addItemListener(this);
Then the methods at the bottom pick up the events and we do what we like with them. In this example, we add them to the JTextArea on the GUI. The command append() puts the text on the end of the existing text, rather than wiping it and starting again.
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
    // Deals with the Action Events.
    public void actionPerformed(ActionEvent e)
    {
        whitebox.append(e.getActionCommand() + " Selected \n");
    }

    // Deals with the Item Events.
    public void itemStateChanged(ItemEvent e)
    {     
        if(e.getSource() == cake)
        {
            whitebox.append("Cake Clicked\n");
        }
        else if(e.getSource() == sorbet)
        {
            whitebox.append("Sorbet Clicked\n");
        }
    }
On the next tutorial, we add very cool things called Accelerators and mnemonics.

Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict