我使用以下代码使用swing为java表单创建热键.如果我按ALT + N,ALT + R,ALT + 1,ALT + 2,光标将移动到正确的文本字段,并在相应的文本字段中输入值.它工作正常.我的问题是,我保存并以这种形式退出JButton如果.我按CTRL + S表示同时选择保存按钮如果按CTRL + X表示将选择退出按钮.如何为JButton创建助记符?如何使用以下代码执行CTRL + S,CTRL + X?
提前致谢.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
kle*_*tra 20
您需要在按钮的组件输入映射中注册keyBinding.在代码中(重复你在之前的问题中被告知要做的微妙变体:-)
// 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");
Run Code Online (Sandbox Code Playgroud)
Sun对整个Key Binding问题有很好的描述.你可以在这里找到它:
//编辑
编辑了我的示例代码,因此您只需复制+粘贴它就可以了.包括缺失的要点,感谢您的反馈.
KeyStroke keySave = KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK);
Action performSave = new AbstractAction("Save") {
public void actionPerformed(ActionEvent e) {
//do your save
System.out.println("save");
}
};
JButton b1 = new JButton(performSave);
b1.getActionMap().put("performSave", performSave);
b1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySave, "performSave");
KeyStroke keyExit = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK);
Action performExit = new AbstractAction("Exit") {
public void actionPerformed(ActionEvent e) {
//exit
System.out.println("exit");
}
};
JButton b2 = new JButton(performExit);
b2.getActionMap().put("performExit", performExit);
b2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyExit, "performExit");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32298 次 |
| 最近记录: |