使用swing在java中为JButton创建热键 [英] create hot keys for JButton in java using swing
问题描述
我使用以下代码使用swing为java表单创建热键。如果我按ALT + N,ALT + R,ALT + 1,ALT + 2,光标移动到正确的文本字段,我在相应的文本字段中输入值。它工作正常。我的问题是,我保存并以这种形式退出JButton如果。我按CTRL + S表示同时选择保存按钮如果按CTRL + X表示将选择退出按钮。如何为JButton创建助记符?如何使用以下代码执行CTRL + S,CTRL + X?
I use the following code to create hot keys for the java form using swing. If I press ALT+N,ALT+R,ALT+1,ALT+2 the cursor moves to correct text fields and I enter the value in corresponding Text Fields. It works properly. My problem is, I have Save and exit JButtons in this form if. I press CTRL+S means the Save button will be selected at the same time If i press CTRL+X means the exit button will be selected. How to create mnemonics for JButton? How to do CTRL+S,CTRL+X this using the following code?
提前致谢。
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(tf1);
Name.setDisplayedMnemonic('N');
JLabel Regno = new JLabel("RegNO");
JTextField tf2 = new JTextField(20);
Regno.setLabelFor(tf2);
Regno.setDisplayedMnemonic('R');
JLabel Mark1 = new JLabel("Mark1");
JTextField tf3 = new JTextField(20);
Mark1.setLabelFor(tf3);
Mark1.setDisplayedMnemonic('1');
JLabel Mark2 = new JLabel("Mark2");
JTextField tf4 = new JTextField(20);
Mark2.setLabelFor(tf4);
Mark2.setDisplayedMnemonic('2');
JButton b1 = new JButton("Save");
JButton b2 = new JButton("eXit");
JFrame f = new JFrame();
JPanel p = new JPanel();
p.add(Name);
p.add(tf1);
p.add(Regno);
p.add(tf2);
p.add(Mark1);
p.add(tf3);
p.add(Mark2);
p.add(tf4);
p.add(b1);
p.add(b2);
f.add(p);
f.setVisible(true);
f.pack();
}
}
推荐答案
你需要在按钮的组件输入映射中注册keyBinding。在代码中(重复你在之前的问题中被告知要做的微妙变体: - )
You need to register a keyBinding in the button's component inputmap. In code (repeating a subtle variant of what you have been told to do in your previous questions :-)
// create an Action doing what you want
Action action = new AbstractAction("doSomething") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("triggered the action");
}
};
// configure the Action with the accelerator (aka: short cut)
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
// create a button, configured with the Action
JButton toolBarButton = new JButton(action);
// manually register the accelerator in the button's component input map
toolBarButton.getActionMap().put("myAction", action);
toolBarButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
(KeyStroke) action.getValue(Action.ACCELERATOR_KEY), "myAction");
这篇关于使用swing在java中为JButton创建热键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!