Creating Menus

It is easy in Swing to create menus. First, you create a menu bar to hold each menu. A menu is the little area that drops down out of the menu bar.

//create the menu bar
JMenuBar menuBar = new JMenuBar();

// Create a menu
JMenu menu = new JMenu("Tools");
menuBar.add(menu);

// Create a menu item
JMenuItem hacksaw = new JMenuItem("Hacksaw");
hacksaw.addActionListener(someActionListener);
menu.add(hacksaw);

// Install the menu bar in the frame
frame.setJMenuBar(menuBar);

The main thing to note here is that clicking menu items creates an action event that you need to handle with an ActionListener implementation. There is a good example of using menus in the Garage Text Editor Toolkit example.

Get Java Garage now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.