如何将ShortCut键添加到JTextField?

Aza*_*zad 5 java swing key-bindings jtextfield

我陷入了一些步骤,我无法添加一个Shorcut键,如:CTRL+ SPACE我的程序,我正在搜索一周,我可以找到任何答案.

Nic*_*ppe 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);
    }
}
Run Code Online (Sandbox Code Playgroud)