【问题标题】:Adding JTextField corrupts key bindings添加 JTextField 会破坏键绑定
【发布时间】:2017-12-04 19:27:06
【问题描述】:

我在创建面板和正确设置键绑定时遇到问题。当我将 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");
        }
    }
}

【问题讨论】:

    标签: java swing jtextfield key-bindings


    【解决方案1】:

    问题解决了……

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

    【讨论】:

    • 如果您只想显示文本,请使用 JLabel。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多