我卡在某个步骤中,无法添加快捷键,例如:CTRL+SPACE 到我的程序,我正在搜索一个星期,但我不能找不到任何 答案。
最佳答案
您需要查看 Java Tutorial以获得对键绑定(bind)的良好概述。
这是一个简单的例子:
import java.awt.event.*;
import javax.swing.*;
public class KeyBindings extends Box{
public KeyBindings(){
super(BoxLayout.Y_AXIS);
final JTextPane textArea = new JTextPane();
textArea.insertComponent(new JLabel("Text"));
add(textArea);
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText("New Text");
}};
String keyStrokeAndKey = "control SPACE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
textArea.getInputMap().put(keyStroke, keyStrokeAndKey);
textArea.getActionMap().put(keyStrokeAndKey, action);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new KeyBindings());
frame.pack();
frame.setVisible(true);
}
}
关于java - 如何为 JTextField 添加快捷键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979667/