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;
}
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.
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.
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 trying to code a game similar to Mario in Java and am having problems with making the dude jump while he is running. What the below code ends up doing is, as the user is holding down right and presses the jump button, Mario basically stops running and jumps, so its like the user has let go of right and pressed jump.
public void keyPressed(KeyEvent e) {
// here I keep track of what buttons the user pressed
int keyCode = e.getKeyCode();
if(keyCode == 37)
pressedKeys[0] = true;
else if(keyCode == 39)
pressedKeys[1] = true;
else if(keyCode == 68)
pressedKeys[2] = true;
// after I see what the user has pressed an action is carried out
Thread t = new Thread(this);
t.start();
}
public void performAction()
{
// depending on what the user has pressed a certain action is performed
if(pressedKeys[2]==true)
{
// changes the coordinates of the character itself
// done in another thread so the background can continue
// moving as the user holds down a direction
Thread t = new Thread(mcControl);
t.start();
}
if(pressedKeys[0]==true)
{
changeSprite();
bg.moveImageForward();
}
if(pressedKeys[1]==true)
{
changeSprite();
bg.moveImageBackward();
}
}
public void run() {
performAction();
}
if(keyCode == 37)
Not related to your problem, but NEVER use code like that. Most people don't know what that magic number means.
The better way to do this is to use:
if(keyCode == KeyEvent.VK_???)
Now your code is self documenting.
You want to take a look at How to Write a Key Listener. The KeyEvent object has several methods for learning what modifier keys and mouse buttons were pressed at the time the event was generated.
public void itemStateChanged(ItemEvent event)
{
if(event.getSource() == doctorBox)
{
if (doctorBox.isSelected() == true)
JOptionPane.showMessageDialog(null, "you are a doctor");
else if (doctorBox.isSelected() != true)
JOptionPane.showMessageDialog(null, "you are not a doctor");
}
}
when the application is run... the checkbox is by default unchecked
when I check the "doctorBox" ... I get two dialog boxes popping together: "you are a doctor" and "you are not a doctor", also the checkbox doesn`t get checked!
why does that happen? how do I change the code to work correctly?
Here are some great samples. Remove all CheckBoxes except one and make sure you have a single listener to a single CheckBox per the details at the provided link. My guess is that there is strangeness occurring due to the way in which the listeners have been added in conjunction with the CheckBoxes.
Couple things to help you
for your logic, Since you know that the choice is either on or off, try the following
if(doctorBox.isSelected())
//do something
else
//do something else
with the checkbox not getting selected, change from an ItemListener to an ActionListener.
private class aListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == doctorBox){
if(doctorBox.isSelected())
JOptionPane.showMessageDialog(null, "you are a doctor");
else {
JOptionPane.showMessageDialog(null, "you are not a doctor");
}
}
}
}
If you look at your current code, and step through it using a debug you will see that your ItemListener gets fired 2 times. The first time checks it, the 2nd time it unchecks it. All on a single click. I cant explain the inner working of an itemListener in this case. ActionListener works much better