Accelerator/Mnemonic Keys in Swing

  

  Creating Accelerator (or Menmonic) Keys in Swing in easy, but a little tricky. This article explains how you would do that

What are accelerator Keys?
   Try pressing alt+d, in your browser now, it will take you to the link bar. This means that the link bar has an Accelerator Key of ‘d’. In your Swing application, you can have any Component have an Accelerator key. This article teaches you to create an application as below
Accelerator Keys in Swing

   Ok, So the first thing you need to learn is that in Swing, you add Mnemonic Keys to labels, not components. The “setDisplayedMnemonic” method in JLabel is used for this. Then you associate this label to a particular component that will get focus when the mnemonic Key set in the Label is Pressed.

   Here’s the code snipped that would set the mnemonic Key of ‘f’ to a Text Field

  JLabel label = new JLabel();
  label.setText("Accelerator Key: f");
 
  //Note this, We set the Mnemonic key for Label, not the text field
  label.setDisplayedMnemonic('f');
 
  JTextField field = new JTextField("Press alt+'f' to focus on this Field ");
  //Here we associate the Field and the text Field
  label.setLabelFor(field);
  //that's it

You can download the Full source code here







3 Responses to 'Accelerator/Mnemonic Keys in Swing'

  1. Anonymous - May 23rd, 2008 at 4:54 pm

    Thanks

  2. pradeep - September 18th, 2008 at 2:28 pm

    Thanks a lot

  3. Loyd Dawson - November 13th, 2008 at 12:26 am

    mcvm8urydd5k1ks4


Leave a Reply





Popular Articles

Blog Categories

Monthly Archives

Resources