Java JButton set mnemonic key for button

Introduction

Button mnemonic is a keyboard shortcut.

JButton closeButton = new JButton("Close");
closeButton.setMnemonic('C');

//or

JButton closeButton = new JButton("Close");
closeButton.setMnemonic(KeyEvent.VK_C);
import java.awt.FlowLayout;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame {

  public Main() {
    super("demo from demo2s.com");
    /*w  w  w .j a  v  a 2 s  . c o  m*/
    // Create icons
    
    JButton closeButton = new JButton("Close");
    closeButton.setMnemonic('C');
    
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setLayout(new FlowLayout());

    getContentPane().add(closeButton);

    closeButton.addActionListener(e -> System.exit(0));
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related