O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required