javacodex.com
Java Examples
Java Examples
memu home questions

Menus

A menu component is used to provide a list of actions to the user in a compact form. You can also provide a list of actions by using a group of JButtons, where each JButton represents an action. It is a matter of preference to use a menu or a group of JButtons to present a list of actions. However, there is a noticeable advantage to using a menu; it uses much less space on the screen compared to a group of JButtons. A menu uses less space by folding (or nesting) a group of options under another option. For example, if you have used a file editor, the options such as New, Open, Save, and Print are nested under a top-level File menu option. A user needs to click the File menu to see the list of options that are available under it. Typically, in case of a group of JButtons, all JButtons are visible to the user all the time, and it is easy for users to know what actions are available. Therefore, there is a little tradeoff between the amount of space and usability when you decide to use a menu or JButtons.

Source: (MenuExample.java)

import java.awt.*;
import javax.swing.*;
 
public class MenuExample {
 
  public static void main(String[] arguments) {
 
    // main window
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JMenuBare Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200,250); 
    frame.setLayout(new BorderLayout());
 
    JMenuBar bar = new JMenuBar();
 
    // add 2 items to menu 2
    JMenu m1 = new JMenu("Menu1", true);
    JMenuItem mi1 = new JMenuItem("New");
    m1.add(mi1);
    JMenuItem mi2 = new JMenuItem("Open");
    m1.add(mi2);
    m1.addSeparator();
    JMenuItem mi3 = new JMenuItem("Exit");
    m1.add(mi3);
 
    // add 4 items to menu 2
    JMenu m2 = new JMenu("Menu2", true);
 
    JMenuItem mi4 = new JMenuItem("Cut");
    m2.add(mi4);
    JMenuItem mi5 = new JMenuItem("Copy");
    m2.add(mi5);
    JMenuItem mi6 = new JMenuItem("Paste");
    m2.add(mi6);
    JMenuItem mi7 = new JMenuItem("Move");
    m2.add(mi7);
    mi7.setEnabled(false);
 
    m2.addSeparator();
 
    JRadioButtonMenuItem rb1 = new JRadioButtonMenuItem("RB1");
    m2.add(rb1);
    JRadioButtonMenuItem rb2 = new JRadioButtonMenuItem("RB2");
    m2.add(rb2);
 
    // add two menus to bar
    bar.add(m1);
    bar.add(m2);
 
    frame.add(bar,BorderLayout.NORTH);
    frame.setVisible(true);
  }
}
 

Output:


Output



Contact: javacodex@yahoo.com