Select the JComboBox by choosing the nearby label using Mnemonic key in Java

Description

The following code shows how to select the JComboBox by choosing the nearby label using Mnemonic key.

Example


import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/* www. j  av  a2 s .c om*/
import javax.swing.Box;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JPanel {
  public Main() {
    JLabel lbl = new JLabel("Color:");
    lbl.setDisplayedMnemonic('c');
    add(lbl);
    add(Box.createHorizontalStrut(20));
    JComboBox cbColor = new JComboBox();
    cbColor.addItem("red");
    cbColor.addItem("blue");
    lbl.setLabelFor(cbColor);
    add(cbColor);
  }

  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    f.getContentPane().add(new Main());
    f.pack();
    f.setSize(new Dimension(300, 200));
    f.show();

  }
}

The code above generates the following result.

Select the JComboBox by choosing the nearby label using Mnemonic key in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer