I want to know how to add shortcuts similar to Emacs's in my Java application. For example C-x C-f and C-x b.
Thanks.
Java provides a means to identify Modifier keys.
By Modifier keys I mean
Alt -- e.isAltDown();
Ctrl -- e.isControlDown();
Shift -- e.isShiftDown()
These acan be paired with other normal key press buttons from your keyboard to identify whether a combination has been pressed.
if( (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_X) )
{
}
e.getModifiers() can be used to identify the modifier as well as the mouse button clicked. This returns bit mask.
See here. http://www.leepoint.net/notes-java/GUI-lowlevel/keyboard/keyboard.html
I would use it something like this for Ctrl. This is overly simplified code, but you will get an idea.
JTextField sampleTxtFld= new JTextField();
sampleTxtFld.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{
if((e.isControlDown() && e.getKeyCode() == KeyEvent.VK_X)
{
//identifies whether Ctrl + X has been pressed
// do some action here
}
}
public void keyReleased(KeyEvent e)
{
//some key released code here
}
public void keyTyped(KeyEvent e) {
}
});
As far as I know EMACS is an editor. If you want to change the KeyStrokes for editing command on Swing text components then you need to use Key Bindings. You can use the existing text Actions but just bind them to different KeyStrokes. See Key Bindings for a list of all the default bindings an some example of how to rebind and Action.
Related
I have a requirement where need to mask the value entering into jText area at runtime. I am able to achieve this but problem is scenario with backspace. When I press back space sequentially (one by one) then it work while if I kept pressing then its counting the event as one and removing only one character (by considering the key event as one key released).
Here my code snippets is :
public void showPrompt() throws InterruptedException {
sem.acquire();
this.toFront();
this.setAlwaysOnTop(true);
this.setVisible(true);
if(encryptKeystroke == true) {
jTextArea.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (e.getExtendedKeyCode() == KeyEvent.VK_BACK_SPACE) {
text = text.substring(0, text.length() - 1);
}
else {
text += String.valueOf(e.getKeyChar());
}
jTextArea.setText(text.replaceAll(".", "*"));
}
});
}
}
Is there any way if I kept pressing the backspace then it should remove all the characters irrespective of considering it one key event ?
As you have said in the comment that the requirements are not exactly like the password and so you won't be using JPasswordField, I would like to give a solution for the question.
Here, the code to detect a backspace key stroke is written inside the keyReleased() method. Now, the keyReleased() method will be called by the keyListener when you will pull your finger up from a key in this case your backspace key. That is why even if you continuously keep pressing the backspace key, it will execute the code only once i.e. only when you release the key.
Now, you wish to remove one character every time backspace is pressed so you can just move your code from the keyReleased() method to the keyPressed() method.
If you move the code inside the keyPressed() method, then the code will be executed at every key stroke even if you continuously keep pressing the backspace key.
i have a button that call a method, in this method it call another method to connect to the DB and return results, if results positive, change the labels and make a button ENABLED, and if the results is negative, the Button still disabled
the problem is, i have set in the TF a keytyped event, if someone type something new in it, disable the btnEditar:
public void keyTyped(KeyEvent e) {
btnEditar.setEnabled(false);
btnDeletar.setEnabled(false);
}
i dont want this event "capture" the enter to disable the button
there is a way to do that or i have to think i another logic way?
As others have pointed out, there are other ways to do this besides using a KeyListener. I will respond to your original attempt below. A KeyListener is a functional and easy tool to use for this job.
Use keyPressed instead of keyTyped, and then you'll have a valid key code that you can use to ignore enter presses:
public void keyPressed(KeyEvent e) { // not keyTyped!
if (e.getKeyCode() != KeyEvent.VK_ENTER) {
btnEditar.setEnabled(false);
btnDeletar.setEnabled(false);
}
}
If you insist on using keyTyped for some reason, you won't have a key code available, but you can cover most cases by checking the character for a newline or carriage return:
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() != 13 && e.getKeyChar() != 10) {
btnEditar.setEnabled(false);
btnDeletar.setEnabled(false);
}
}
Use a DocumentListener to listen for changes to the text in the Document. Read the section from the Swing tutorial on How to Write a Document Listener.
I'm working on a JTexfield which sets its own text to the name of the key pressed when it has the focus on the window. I've managed to let it have only a word with the code:
#Override
public void keyReleased(KeyEvent ev) {
if (ev.getKeyCode() != 0) {
keyTrigger = ev.getKeyCode();
txtTrigger.setText(ev.getKeyText(keyTrigger));
}
}
#Override
public void keyTyped(KeyEvent ev) {
txtTrigger.setText("");
}
However it looks horrible when you press special keys like F1--12 or Ctrl because it keeps the last typed non-special key (for example, if you press 'T' and then 'Ctrl', the text in the field keeps being 't' until you release the 'Ctrl' key).
This is the code so far for the JTextField:
txtTrigger = new JTextField();
txtTrigger.setColumns(10);
txtTrigger.addKeyListener(this);
txtTrigger.setBounds(80, 5, 64, 20);
contentPane.add(txtTrigger);
What I want is the field to be empty until you release the key. How can I get the application working this way?
I don't think a editable text field is your best choice here. What I've done in the past is basically faked it.
I've generated a custom component that "looks" like a JTextField and, using my own KeyListener, I've added elements to the view (I did my own "key" renderer, but you could simply have a list of String elements that you can render).
Basically, when keyPressed is triggered, I would add the key code to a list (taking into consideration things like its modifier state). If another key event is triggered with the same key code, then you can ignore it.
When keyReleased is triggered, you can remove that keycode from the active list.
You can add the keylistener to the jframe or many components...
Just make sure that component has the focus.
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!
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.
ChatGUI
im using 2 JEditorPane to transfer text from one to another.
once i have transfered the data i do the following:
JEditorPane.setText(null);
JEditorPane.setCaretPosition(0);
but as you can see from the attached image the return action makes the prompt appear a row down. how can i fix this?
EDIT: does the following seem correct to you? if so then why is caret not positioning itself to chracter 0 position?
private class MyKeyAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent ke) {
int kc = ke.getKeyCode();
if (kc == ke.VK_ENTER) {
System.out.println(editorPaneHistory.getText());
System.out.println(editorPaneHomeText.getText());
editorPaneHistory.setText(editorPaneHomeText.getText());
//JEditorPane - editorPaneHistory
//JEditorPane - editorPaneHomeText
editorPaneHomeText.setText(null);
editorPaneHomeText.setCaretPosition(0);
}
}
}
After your code runs, the JEditorPane is reacting to the enter key in the usual way, by inserting a newline. Try calling ke.consume() to "consume" the event so that the JEditorPane itself doesn't handle it.
Don't use a KeyListener. You should be using a custom Action. This way you can replace the default Action. Read up on Key Bindings.