Java Swing How to - Add Mnemonic Key Radio Button








Question

We would like to know how to add Mnemonic Key Radio Button.

Answer

/*  w w  w .  j  a  va 2 s.co  m*/
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;

public class Main {
  public static void main(String[] args) {
    
    JRadioButton button1 = new JRadioButton("Red");
    JRadioButton button2 = new JRadioButton("Green");
    
    button2.setMnemonic(KeyEvent.VK_G);
    
    JRadioButton button3 = new JRadioButton("Blue");
    ButtonGroup colorButtonGroup = new ButtonGroup();
    colorButtonGroup.add(button1);
    colorButtonGroup.add(button2);
    colorButtonGroup.add(button3);
    button1.setSelected(true);

    JFrame frame = new JFrame();
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(new JLabel("Color:"));
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.pack();
    frame.setVisible(true);
    
    
  }
}