'Changing the value of a variable using the keyListener in Java
I was working on an exercise where a boolean variable is required to set to true if a certain key is pressed and false otherwise via my class. Later in main, if the value of this variable is true it must carry out instructions. I wrote my own code, but apparently it doesn't work...
Main:
package DroneController;
public class Main {
public static void main(String[] args) {
DroneController TelloController = new DroneController();
while(true) {
System.out.println("Key no pressed.");
if (TelloController.keyPressed) System.out.println("Key pressed.");
}
}
}
Class:
package DroneController;
import javax.swing.JFrame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class DroneController extends JFrame implements KeyListener {
public boolean keyPressed;
DroneController(){
this.setSize(400,200);
this.setTitle("DroneController");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(this);
this.setFocusable(true);
this.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar()=='A' || e.getKeyChar()=='a') {
keyPressed = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar()=='A' || e.getKeyChar()=='a') {
keyPressed = false;
}
}
}
How is it possible that it doesn't print "Key Pressed" when I press the A key?
Solution 1:[1]
You need to rethink your approach. Event programming is about testing when something happens, not when it doesn't happen. If you want an action to occur when an event occurs then you need to notify the appropriate controller. For example:
JFrame frame = new JFrame("Drone Controller");
frame.setSize(400,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(new KeyAdapter() {
boolean keyDown = false;
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_A) {
keyDown = true;
}
outputStatus();
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_A) {
keyDown = false;
}
outputStatus();
}
public void outputStatus() {
if (keyDown) {
System.out.println("Key is pressed.");
} else {
System.out.println("Key is not pressed.");
}
}
});
frame.setFocusable(true);
frame.setVisible(true);
This will simply output when the 'a' key is pressed and released. If you hold it down, then you'll get it spamming pressed notification.
If you want an action to occur, like if you're doing a WASD setup for controls, you'd trap for A and then fire off a notificiation that the drone should go left. Trap for D for and fire off a notification to go right. The DRONE should become the key listener.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ryan |
