Java Swing Tutorials - Herong's Tutorial Examples - v4.32, by Herong Yang
MenuBarTest.java - AWT Menu Bar Test Program
This section provides a tutorial example on how to use the java.awt.MenuBar class to create a menu bar in a frame window.
If you want to add a menu bar to a AWT frame, you can follow this example program:
/* MenuBarTest.java * Copyright (c) 1997-2024 HerongYang.com. All Rights Reserved. */ import java.awt.Frame; import java.awt.MenuBar; import java.awt.Menu; import java.awt.MenuItem; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MenuBarTest { public static void main(String[] a) { Frame f = new Frame("MenuBar Test"); f.setBounds(50,50,250,150); MenuBar mb = new MenuBar(); mb.add(new Menu("Tools")); mb.add(new Menu("Options")); mb.add(new Menu("Save")); mb.add(new Menu("Quit")); f.setMenuBar(mb); f.add(new MyButton()); f.setVisible(true); } private static class MyButton extends Button implements ActionListener { public MyButton() { super("Check"); addActionListener(this); } public void actionPerformed(ActionEvent e) { System.out.println("Check button clicked"); Frame myFrame = (Frame) (this.getParent()); MenuBar myMenuBar = myFrame.getMenuBar(); System.out.println("# of elements in the menu bar: " +myMenuBar.getMenuCount()); } } }
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, you will see text output in the console window:
Check button clicked # of elements in the menu bar: 4
Interesting notes about this tutorial example:
Note that there seems to be a problem with the f.setMenuBar(mb) call on macOS computers. It fails to display the menu bar as shown below. And it does not give out any error.
Table of Contents
Introduction of Java Swing Package
Graphics Environment of the Local System
JCheckBox - Swing Check Box Class
JRadioButton - Swing Radio Button Class
JTextField - Swing Text Field Class
JComboBox - Swing Combo Box Class
Menu Bar, Menus, Menu Items and Listeners
Creating Internal Frames inside the Main Frame
Layout of Components in a Container
JEditorPane - The Editor Pane Class
SwingWorker - The Background Task Worker
►AWT (Abstract Windows Toolkit)
What Is AWT (Abstract Windows Toolkit)
HelloAWT.java - My First AWT Program
Closing AWT Frame and Terminating Application
Drawing Graphics - Using paint() on Frame or Component
Creating Labels with java.awt.Label Class
Creating Buttons with java.awt.Button Class
AWT Button Action Handler at the Component Level
AWT Button Action Handler at the Frame Level
AWT Button Mouse Click Handler at the Frame Level
AWT TextField and ActionListener
►MenuBarTest.java - AWT Menu Bar Test Program
MenuTest.java - AWT Menu Test Program
MenuItemTest.java - AWT Menu Item Test Program
MenuItemActionListenerTest.java - AWT Menu Item Action Listener