Create hotkeys in java with swing

Hi, I wrote the following code to create hotkeys in java Swing. I am creating Mnemonic for Jtextfield1 (Name) . He showed it correctly, but now I need to know that when I start, I immediately press tf2 , then the cursor will take the value tf2 from tf1 .

I enter some values ​​in tf2 . Then I need to enter tf1 . In this situation, I press ALT+N (because N is mnemonic tf1 ). The cursor focused tf1 and entered the name in the text box. how to do it?

 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(); } } 
0
source share
2 answers

you need to look for KeyBindings , the output from KeyBindings should be javax.swing.Action , and there you can wrap the Focus set in JComponent solutions,

+2
source

The need you are describing is mnemonic for JTextField. For AbstractButton derivatives, you set mnemonics directly with setMnemonic . For JTextField, you create a JLabel and set the mnemonics in JLabel. Then you attach the label to the text box, and the mnemonics works as expected. You attach the label to the text field as follows:

 label.setLabelFor(textField); 

So, the only thing that is wrong in your code is that you entered the wrong argument in the setLabelFor call.

+1
source

Source: https://habr.com/ru/post/1387354/


All Articles