开发者

Java: Register <ENTER> key press on JTextPane

I'm making an application with java that has a JTextPane. I want to be able to execute some code when the enter key is pressed (or when the user goes to the next line). I've looked on the web and not found a solution. Would it be better to tackle this with C#? If not, how can i register the Enter key in the JTextPane's keyTyped() event? If C# is a good option, how would i do this in C#?

Here is a solution i thought would work...but did not

开发者_JAVA技巧
//Event triggered when a key is typed
private void keyTyped(java.awt.event.KeyEvent evt) {
    int key = evt.getKeyCode();
    if (key == KeyEvent.VK_ENTER) {
        Toolkit.getDefaultToolkit().beep();
        System.out.println("ENTER pressed");
    }
}

Why the above example does not work is because no matter which key i press, i get a keyCode of 0. I would prefer a solution to this problem in Java but C# would work just as well, maybe better. Also, please try to answer the question with examples and not links(unless you really need to). Thanks!


One solution is to add a key binding on the textpane. e.g.,

  JTextPane textPane = new JTextPane();

  int condition = JComponent.WHEN_FOCUSED;
  InputMap iMap = textPane.getInputMap(condition);
  ActionMap aMap = textPane.getActionMap();

  String enter = "enter";
  iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enter);
  aMap.put(enter, new AbstractAction() {

     @Override
     public void actionPerformed(ActionEvent arg0) {
        System.out.println("enter pressed");
     }
  });


This answer is in case anyone ever views this thread I got the same things as Mr. Mohammad Adib.

So instead of using ...

(evt.getKeyCode()==evt.VK_ENTER)

I used ...

(evt.getKeyChar()=='\n')

and the solution worked.


I am looking for ENTER key in the password text field, to launch the login method when ENTER was pressed. The code below will print in the console the keycode. After running the program and typing a few tihngs in the box I discovered for ENTER key it is code 13.

    txtPass = new Text(shlLogin, SWT.BORDER | SWT.PASSWORD);
    txtPass.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println(e.keyCode);
            if (e.keyCode == 13) { /* ... Do your stuff ... */ }
        }
    });

If you are looking for a single key press, you can still be a little lazy and avoid learning new stuff about key bindings, by using this method. The fun begins when adding CTRL+[Letter] shortcuts - but this is for another discussion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜