Java: Register <ENTER> key press on JTextPane
Solution 1
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");
}
});
Solution 2
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.
Related videos on Youtube
Mohammad Adib
Email: [email protected] Facebook: http://fb.com/mohammad.a.adib Programming languages: Java, C# Occupation: Robotic Engineer at Wicresoft Workspace: Core i7-3770k @ 4.7ghz, 16gb RAM @ 1875mhz
Updated on June 05, 2022Comments
-
Mohammad Adib about 2 years
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!
-
trashgod almost 13 years+1 for key bindings, although the default insert-break action will be lost.
-
kleopatra almost 13 years@trashgod true, but the requirement is not fully clear, could be a) replace default behaviour or b) add to the default behaviour For b) simply wrap the the default and trigger in the custom