Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 714
Mohammad Adib Avatar asked Sep 16 '11 01:09

Mohammad Adib


2 Answers

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");
     }
  });
like image 127
Hovercraft Full Of Eels Avatar answered Oct 19 '22 15:10

Hovercraft Full Of Eels


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.

like image 23
PaRaD0X Avatar answered Oct 19 '22 15:10

PaRaD0X