如何将ShortCut键添加到JTextField?

时间:2012-12-20 20:07:23

标签: java swing jtextfield key-bindings

我被困在一些步骤,我无法添加快捷键,如: CTRL + SPACE 到我的程序,我正在搜索一周而我无法找不到任何东西 答案。

1 个答案:

答案 0 :(得分:7)

您需要查看Java Tutorial以获得关键绑定的详细概述。

这是一个简单的例子:

import java.awt.event.*;
import javax.swing.*;

public class KeyBindings extends Box{
    public KeyBindings(){
        super(BoxLayout.Y_AXIS);
        final JTextPane textArea = new JTextPane();
        textArea.insertComponent(new JLabel("Text"));
        add(textArea);

        Action action = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.setText("New Text");
            }};
         String keyStrokeAndKey = "control SPACE";
         KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
         textArea.getInputMap().put(keyStroke, keyStrokeAndKey);
         textArea.getActionMap().put(keyStrokeAndKey, action);
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new KeyBindings());
        frame.pack();
        frame.setVisible(true);
    }
}
相关问题