This section provides a tutorial example on how to use the javax.swing.JMenuBar class to create a menu bar in a frame window. Menus and menu items added to the menu bar will be listed horizontally.
Here is an example program I wrote to test the JMenuBar class:
/**
* JMenuBarTest.java
* Copyright (c) 2009 by Dr. Herong Yang, http://www.herongyang.com/
*/
import java.awt.event.*;
import javax.swing.*;
public class JMenuBarTest {
public static void main(String[] a) {
JFrame f = new JFrame("JMenuBar Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(50,50,250,150);
JMenuBar mb = new JMenuBar();
mb.add(new JMenu("Tools"));
mb.add(new JMenu("Options"));
mb.add(new JMenuItem("Save"));
mb.add(new JMenuItem("Quit"));
mb.add(new JButton("Stop"));
f.setJMenuBar(mb);
f.getContentPane().add(new MyButton());
f.setVisible(true);
}
private static class MyButton extends JButton
implements ActionListener {
public MyButton() {
super("Check");
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Check button clicked");
JFrame myFrame = (JFrame)
(this.getParent().getParent()).getParent().getParent();
JMenuBar myMenuBar = myFrame.getJMenuBar();
System.out.println("# of elements in the menu bar: "
+myMenuBar.getMenuCount());
System.out.println("Is the menu bar selected: "
+myMenuBar.isSelected());
}
}
}
If you run this example, you will see the frame window shows up with the menu bar like this:
If you click the "Check" button, click the "Options" menu in the menu bar, and click the "Check" button again,
you will see text output in the console window:
C:\herong\swing_20051029\cod>java JMenuBarTest
Check button clicked
# of elements in the menu bar: 5
Is the menu bar selected: false
Check button clicked
# of elements in the menu bar: 5
Is the menu bar selected: true
Interesting notes about this tutorial example:
JMenuItem objects can be added to the menu bar in the same as JMenu objects.
Other components can also be added to the menu bar. See the "Stop" JButton object added in the example program.
The "Check" JButton added in the content pane is a grand grand grand child of the frame. So there are 3 layers
of component in the content pane, because I have to use "this.getParent().getParent()).getParent().getParent()"
to reach the frame object from the button object.
getMenuCount() and isSelected() methods work as expected.
Sample programs listed in this section have been tested with JDK 1.6.0.