我使用带有swing库的Java代码为按钮分配了键盘快捷键。如果在输入之前单击文本字段,它将写入2次。我想写一次。
Java代码:
button1 = new JButton("1");
button1.addActionListener(this);
button1.setBackground(Color.lightGray);
//button1 normal number button
button1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "button1");
button1.getActionMap().put("button1", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "1");
}
});
//button1 numpad number button
button1.getInputMap(button1.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD1, 0), "button1");
button1.getActionMap().put("button1", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "1");
}
});
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getActionCommand().equals("1")){
textField.setText(textField.getText() + "1");
}
}
您可以在屏幕快照中看到,当选择了文本字段时,我按下了按钮1一次,但是写了2次。
您的最后一个方法看起来很多余。
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getActionCommand().equals("1")){
textField.setText(textField.getText() + "1");
}