添加JTextField会破坏密钥绑定

时间:2017-12-04 19:27:06

标签: java swing jtextfield key-bindings

我在创建面板时遇到问题,并正确设置了键绑定。当我将JTextField添加到我的JFrame时,我的键绑定会停止工作。因此,例如,SSCCE显示我的问题 - 如果您对包含JTextField的行进行注释,则按p将按预期工作。为什么会发生这种情况,我该如何解决这个问题?

import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class Example{
    Example(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);

        JPanel panel = new JPanel(true);
        panel.setBackground(Color.BLACK);
        panel.setLayout(new FlowLayout());
        panel.setPreferredSize(new Dimension(500, 500));
        panel.setBorder(BorderFactory.createEmptyBorder()); 
        panel.setFocusable(true); 
        frame.add(panel, BorderLayout.SOUTH);
        KeyboardInput keyboard = new KeyboardInput(panel);

        // adding JTextField corrupts key bindings
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(500, 100));
        textField.setFont(textField.getFont().deriveFont(15));
        textField.setText("text");
        textField.setEditable(false);
        textField.setFocusable(true);
        textField.setBorder(BorderFactory.createEmptyBorder());
        textField.setBackground(Color.BLACK);
        frame.add(textField, BorderLayout.NORTH);

        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);            
    }

    public static void main(String[] args){
        new Example();
    }
}

class KeyboardInput{
    KeyboardInput(JPanel panel){
        InputMap inMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        ActionMap actMap = panel.getActionMap(); 
        inMap.put(KeyStroke.getKeyStroke("P"), "pauseGame");
        actMap.put("pauseGame", new pauseAction());
    }

    class pauseAction extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("PAUSE");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题解决了......

textField.setFocusable(true);应更改为textField.setFocusable(false);