关于写两次Java键的问题

问题描述 投票:0回答:1

我使用带有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");
    }
}

sample screenshot

您可以在屏幕快照中看到,当选择了文本字段时,我按下了按钮1一次,但是写了2次。

java swing key-bindings
1个回答
0
投票

您的最后一个方法看起来很多余。

public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getActionCommand().equals("1")){
    textField.setText(textField.getText() + "1");
}
© www.soinside.com 2019 - 2024. All rights reserved.