What is meant by accelerator keys? Explain application with proper java code.
Accelerator Key
Accelerator: is a key combination (Ctrl key + letter or function key) which is, if pressed, will trigger action listener associated with the menu or button. For example: F5, Ctrl + O, Ctrl + F5, etc. The associated menu is not displayed if accelerator shortcut is used. The key combination is displayed next to the menu item.
Set Accelerator key for JMenuItem in Java
The following code shows how to set Accelerator key for JMenuItem.
Example
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
public class Main {
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->Paste, P - Mnemonic, CTRL-V - Accelerator, Disabled
JMenuItem pasteMenuItem = new JMenuItem("Paste", KeyEvent.VK_P);
KeyStroke ctrlVKeyStroke = KeyStroke.getKeyStroke("control V");
pasteMenuItem.setAccelerator(ctrlVKeyStroke);
fileMenu.add(pasteMenuItem);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
The code above generates the following result.
Comments
Post a Comment