Java: Register <ENTER> key press on JTextPane

Mohammad Adib picture Mohammad Adib · Sep 16, 2011 · Viewed 19.1k times · Source

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

//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!

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Sep 16, 2011

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