【问题标题】:How To Add ShortCut Keys to JTextField?如何向 JTextField 添加快捷键?
【发布时间】:2012-12-20 20:07:23
【问题描述】:

我卡在某个无法添加快捷键的步骤中,例如:CTRL+SPACE 到我的程序中,我正在搜索一个星期,我可以会找到任何 答案。

【问题讨论】:

标签: java swing jtextfield key-bindings


【解决方案1】:

您需要查看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);
    }
}

【讨论】:

  • 猜猜看!它奏效了。感谢您的建议和解决方案,它与 JTextField 相同,我将查找 keyBindings 。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 2023-03-23
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多