Java Swing How to - Create Submenu on the Main menu
Java Swing How to - Create Submenu on the Main menu
Menus are unique in that, by convention, they aren't placed with the other components in the UI. Instead, a menu usually appears either in a menu bar or as a popup menu. A menu bar contains one or more menus and has a customary, platform-dependent location — usually along the top of a window. A popup menu is a menu that is invisible until the user makes a platform-specific mouse action, such as pressing the right mouse button, over a popup-enabled component. The popup menu then appears under the cursor.
import javax.swing.*;
import java.awt.event.KeyEvent;
public class SubMenuExample {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
// File Menu, F - Mnemonic
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
// File->New, N - Mnemonic
JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(newMenuItem);
// Edit->Options Submenu, O - Mnemonic, at.gif - Icon Image File
JMenu findOptionsMenu = new JMenu("Options");
Icon atIcon = new ImageIcon("at.gif");
findOptionsMenu.setIcon(atIcon);
findOptionsMenu.setMnemonic(KeyEvent.VK_O);
fileMenu.add(findOptionsMenu);
// ButtonGroup for radio buttons
ButtonGroup directionGroup = new ButtonGroup();
// Edit->Options->Forward, F - Mnemonic, in group
JRadioButtonMenuItem forwardMenuItem = new JRadioButtonMenuItem("Forward", true);
forwardMenuItem.setMnemonic(KeyEvent.VK_F);
findOptionsMenu.add(forwardMenuItem);
directionGroup.add(forwardMenuItem);
// Edit->Options->Backward, B - Mnemonic, in group
JRadioButtonMenuItem backwardMenuItem = new JRadioButtonMenuItem("Backward");
backwardMenuItem.setMnemonic(KeyEvent.VK_B);
findOptionsMenu.add(backwardMenuItem);
directionGroup.add(backwardMenuItem);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
Image 1 |
Image 2 |
Comments
Post a Comment