按下F2时,ActionMap / InputMap使JTextArea显示“此文本”

时间:2013-10-30 19:25:18

标签: java swing jtextfield key-bindings key-events

在某个TextField中按下F2时,我一直试图让JTextArea显示某个字符串,但还没有成功。任何帮助非常感谢。

我的代码可能揭示了我的编程经验:

final String ACTION_KEY = "this text";

public void actionPerformed(ActionEvent actionEvent) {

                JTextField source = (JTextField) actionEvent.getSource();

                System.out.println("Activated: " + source.getText());

                textAreaInstructions.setText("this text");

              }
            };


            KeyStroke F2 = KeyStroke.getKeyStroke("F2");
            InputMap inputMap = timeStep.getInputMap();
            inputMap.put(F2, ACTION_KEY);
            ActionMap actionMap = timeStep.getActionMap();          
            actionMap.put(ACTION_KEY, actionListener);

编辑:我现在正在尝试使用此代码:

InputMap inputMap = timeStep.getInputMap();
        Object actionSubmit = inputMap.get(KeyStroke.getKeyStroke("ENTER"));
        Object actionSubmitSp = inputMap.get(KeyStroke.getKeyStroke("SPACE"));
        System.out.println("actionSubmit for space = " + actionSubmitSp);
        ActionMap actionMap = timeStep.getActionMap();
        Action action = actionMap.get(actionSubmit);
        System.out.println("actionSubmit = " + actionSubmit);
        timeStep.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),
                actionSubmit);

编辑:

打印

actionSubmit for space = null
actionSubmit = notify-field-accept

这有用吗?

1 个答案:

答案 0 :(得分:0)

问题与发布的代码无关。就是我将文件的备份保存在与原始文件相同的包中,忘记更改代码,因此正在实施备份而不是更新的原始文件。这花了我很多时间。大声笑。

编辑:所以无论如何,既然我知道我正在运行哪个文件,我发现下面的代码(我在这里:http://blog.marcnuri.com/blog/.../2007/06/06/Detecting-Tab-Key-Pressed-Event-in-JTextField-s-Event-VK-TAB-KeyPressed)做了我想要的(对于tab而不是F2,但是显然也适用于F2,在这种情况下不需要第一行):

timeStep.setFocusTraversalKeys(
                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);

        timeStep.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_TAB){
                    instruction = "tab pressed";
                    textAreaInstructions.setText(instruction);
                    lblTabEvent.setText(instruction);
                    // If you want to change the focus to the next component 
                    timerInterval.grabFocus();
            }
                else {

                    textAreaInstructions.setText("got here, "+ e.getKeyCode());
                }
            }

        });