Reputation: 89
Hi I wrote the following code to create hot keys in java Swing. I create the Mnemonic for Jtextfield1 (Name)
. It showed properly, but now I need to know if at run time I immediately click tf2
then the cursor will come to tf2
from tf1
.
I enter some values in tf2
. Then I need to enter tf1
. In this situation I press ALT+N
keys (because N is mnemonic of tf1
). The cursor focused tf1
and entered the name in the textfield. how do I do this?
package hotkeys;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class hotkey extends JFrame {
public static void main(String arg[]) {
JLabel Name=new JLabel("Name");
JTextField tf1=new JTextField(20);
Name.setLabelFor( Name );
Name.setDisplayedMnemonic( 'N' );
JLabel Regno=new JLabel("Reg_NO");
JTextField tf2=new JTextField(20);
JButton b1=new JButton("Save");
JButton b2=new JButton("eXit");
JFrame f=new JFrame();
JPanel p=new JPanel();
p.add(Name);
p.add(Regno);
p.add(tf1);
p.add(tf2);
p.add(b1);
p.add(b2);
f.add(p);
f.setVisible(true);
f.pack();
}
}
Upvotes: 0
Views: 1308
Reputation: 7866
The need you describe is a mnemonic for JTextField. For AbstractButton derivatives you set mnemonic directly with setMnemonic. For JTextField you create a JLabel and set the mnemonic to JLabel. Then you attach the label to the text field and the mnemonic works as expected. You attach the label to the text field like this:
label.setLabelFor(textField);
So the only thing wrong in your code is that you entered wrong argument in the call to setLabelFor.
Upvotes: 1
Reputation: 109815
you have to look for KeyBindings, output from KeyBindings
should be javax.swing.Action and there you can wrap set Focus
to the decisions JComponent
,
Upvotes: 2