Advertisement
RupeshAcharya60

Keyboard Mnemonics and Accelerators

Mar 24th, 2023 (edited)
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | Source Code | 0 0
  1. import javax.swing.*;
  2. import java.awt.event.*;
  3.  
  4. class MnemonicAcceleratorExample extends JFrame {
  5.     public MnemonicAcceleratorExample() {
  6.         setTitle("Mnemonic and Accelerator Example");
  7.         setSize(300, 200);
  8.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  9.  
  10.         JMenuBar menuBar = new JMenuBar();
  11.         setJMenuBar(menuBar);
  12.  
  13.         JMenu fileMenu = new JMenu("File");
  14.  
  15.         fileMenu.setMnemonic(KeyEvent.VK_F);
  16.         menuBar.add(fileMenu);
  17.  
  18.         JMenuItem openMenuItem = new JMenuItem("Open");
  19.         openMenuItem.setMnemonic(KeyEvent.VK_O);
  20.         openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
  21.         fileMenu.add(openMenuItem);
  22.  
  23.         JMenuItem saveMenuItem = new JMenuItem("Save");
  24.         saveMenuItem.setMnemonic(KeyEvent.VK_S);
  25.         saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
  26.         fileMenu.add(saveMenuItem);
  27.  
  28.         openMenuItem.addActionListener(new ActionListener() {
  29.             public void actionPerformed(ActionEvent e) {
  30.                 System.out.println("Open file selected");
  31.             }
  32.         });
  33.  
  34.         saveMenuItem.addActionListener(new ActionListener() {
  35.             public void actionPerformed(ActionEvent e) {
  36.                 System.out.println("Save file selected");
  37.             }
  38.         });
  39.     }
  40.  
  41.  
  42. }
  43.  
  44. public class GUI{
  45.     public static void main(String[] args) {
  46.         MnemonicAcceleratorExample example = new MnemonicAcceleratorExample();
  47.         example.setVisible(true);
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement