JMenuBar : setMnemonic() and addSeparator()

We can add shortcuts for the File and Elements menu items by adding the following statements after you add the menu items to the menu bar:

menu1.setMnemonic(‘F’); // Create shortcut

menu2.setMnemonic(‘E’); // Create shortcut

This method is inherited from the AbstractButton class, so all subclasses of this class inherit this method. The argument is a character from the label for the item that is to be the shortcut character — under Windows, the File menu would then pop up if you key Alt+F. The effect of setMnemonic() is to implement the shortcut and underline the shortcut character letter in the menu label. The shortcut for each menu on the menu bar must be a unique key combination.

addSeparator () :

The separator appears following the previous menu item that you added to the menu.

Program

fsdfd



 
 
 

Program Source

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

class JMenuBarTest extends JFrame {

    JMenuBarTest()
    {
        setTitle("JMenuBar_test");
        setJMenuBarAndMenuBarItems();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    void setJMenuBarAndMenuBarItems()
    {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu1   = new JMenu("File");
        menu1.setMnemonic('F');
        menu1.add(new JMenuItem("New"));
        menu1.addSeparator();
        menu1.add(new JMenuItem("Open"));
        menu1.add(new JMenuItem("Save"));
        menu1.add(new JMenuItem("SaveAs"));
        menu1.addSeparator();
        menu1.add(new JMenuItem("Exit"));
        JMenu menu2   = new JMenu("Edit");
        menu2.setMnemonic('E');
        menu2.add(new JMenuItem("Cut"));
        menu2.add(new JMenuItem("Copy"));
        menu2.add(new JMenuItem("Paste"));
        menuBar.add(menu1);
        menuBar.add(menu2);
        setJMenuBar(menuBar);
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        JMenuBarTest jm = new JMenuBarTest();
    }
}

Leave a Comment