0

当在某个 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

这有什么用吗?

4

1 回答 1

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());
                }
            }

        });
于 2013-10-30T19:52:12.280 回答