Skip keyPressed event - java

How can i skip a keyevent if the typed key is a specific key ( in my case enter) ? When i press enter i want to click on the button and stop there, without continuing the code that comes next in this method. Seems like the "consume()" doesn't work.
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER && button.isDisplayable()){
button.doClick();
arg0.consume();
}}

Just stick a return statement underneath.
arg0.consume();
return;

Read the documentation on the KeyEvent. KeyEvent.consume() doesn't prevent the method from continuing to execute, it prevents any other listener method from executing due to the event.
Arrange the logic of your method so that no other code executes if the key pressed was a return key.

Related

Text editor: if certain key pressed want to cancel key event and give new functionality

I have a JEditorPane with text/html type. When an enter key is pressed with the editor focused, I want to do some checks about the state of the document and then override the enter key default functionality if conditions are met.
I believe this can be done with a KeyListener listening for a key, then consume the event if conditions are met to cancel the key making any change to the input. Testing this idea I'm just trying to consume the key event when any key is pressed. The key listener below is printing output when i press any key, but the characters are still getting inserted into the editor pane.
How can I stop the characters getting inserted altogether?
Thanks for your help.
String content = "";
String type = "text/html";
editor = new JEditorPane(type, content);
editor.setEditorKit(new HTMLEditorKit());
editor.setEditable(true);
editor.setPreferredSize(new Dimension(500, 500));
panel.add(editor);
editor.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e){
System.out.println("huh?");
e.consume();
}
});
EDIT----------
Removed key listener, and added instead
Action enter = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("enter!");
if ( condition == true ){
// default enter key behaviour
}
}
};
editor.getActionMap().put("insert-break", enter);
Ok I got rid of the KeyListener and added this, which prevents the default enter-key functionality which is great. But how would i insert a break (the default enter key behaviour) if my if clause is true?
I can't figure out how to trigger that on the editor programmatically.
You are over thinking it.
We save the Action because we want to invoke the actionPerformed(...) method of the Action.
Assuming the original Action is stored in the variable "original" the code would be:
if (condition == true)
original.actionPerformed( e );

is there any way we can mask the value entering into jText area at runtime and should clear the contents if backspace kept pressed

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.

All ObjectEvents created share similar source information?

Any time that I use an ObjectEvent, every statement in it's "performed" method is called. With ActionEvent, if I put separate action commands from different objects, every action command is called for every object. Similarly, using a public library, jnativehook, it utilizes global screen listening for the keyboard/mouse. There are individual constants defined to describe each key from the keyboard pressed, but each "NativeKeyEvent" (the Object event) performs every command despite conditional statements. In Context:
#Override
public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
NativeKeyEvent e = nativeKeyEvent;
Color col;
Piece.TetColor t;
if(e.getKeyCode() == (NativeKeyEvent.VC_SPACE));
{
System.out.println("Space Pressed");
}
if(e.getKeyCode() == NativeKeyEvent.VC_ESCAPE);
{
System.out.println("Escape Pressed");
}
}
This is the action performed of the NativeKeyEvent. No matter what key I press, it will always print out:
Space Pressed
Escape Pressed
I had this problem earlier in the year with ActionEvents and their event commands but just wrote separate anonymous classes for every case I wanted to handle. I'm very confused and would appreciate any help possible.
There is a simple typo in your method. There should be no semi-colon (;) after your if statement. By putting a semi-colon there, the println statement following it is no longer part of the if statement.
Instead use:
if(e.getKeyCode() == NativeKeyEvent.VC_SPACE)
System.out.println("Space Pressed");
else if(e.getKeyCode() == NativeKeyEvent.VC_ESCAPE)
System.out.println("Escape Pressed");
Or:
switch(e.getKeyCode()) {
case NativeKeyEvent.VC_SPACE:
System.out.println("Space Pressed"); break;
case NativeKeyEvent.VC_ESCAPE:
System.out.println("Escape Pressed"); break;
}

Different Enter and mouse click event

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.

In Java, how to make shortcuts that similar to Emacs?

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.

Categories

Resources