I'm writing a simple program to practice my GUI skills, but I've encountered a problem. I want my program to do something when the ALT key is pressed, and the mouse is clicked. I have a boolean that is set to TRUE in the keyPressed method, and FALSE in the keyReleased method. When I call the mouseClicked method, the boolean is FALSE, even if it is being set to TRUE by the key methods.
Here is keyListener the code:
private boolean altPressed;
//......
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_ALT){
altPressed = true;
System.out.println("ALT pressed. ALT: "+altPressed);
}
}
@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_ALT){
altPressed = false;
System.out.println("ALT released. ALT: "+altPressed);
}
}
and the MouseListener code:
@Override
public void mouseClicked(MouseEvent e) {
int keyCode = e.getButton();
if(keyCode == MouseEvent.BUTTON1){
System.out.println("MOUSE button 1 pressed. ALT: "+altPressed);
}
}
Console output (with some commentary)
ALT pressed. ALT: true //I'm pressing and holding ALT
ALT pressed. ALT: true
MOUSE button 1 pressed. ALT: false //Clicking the mouse
ALT pressed. ALT: true
ALT pressed. ALT: true
ALT released. ALT: false //releasing ALT
Why is the boolean false, even though it is being set to true by the KeyListener method? Hopefully, I'm not missing somehting really obvious. Thanks for helping!