I assigned keyboard shortcuts to buttons using my Java code with swing library. If I click on the text field before typing, it writes 2 times. I want to it writes one time.
Java code:
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");
}
}
You can see in the screenshot, I pressed button 1 once when textfield is selected, but it wrote 2 times.