0

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!

  • How are you using this Listener class? If you have two instances of this class, you can't expect to use the variable `altPressed` across multiple instances. I reckon you are using multiple instances of this class for which `altPressed` variable is initialized to `false` (default in java) – Kaushal Niraula Jun 21 '17 at 21:39
  • [This](https://stackoverflow.com/questions/43238705/how-to-assign-a-shortcut-key-combination-to-a-javafx-dialog) may help. You need to look at Key combinations. – SedJ601 Jun 21 '17 at 21:48
  • @KaushalNiraula Yeah, I have one class that implements both Key and Mouse listeners, and I did something like this: list.addKeyListener(new Main()); list.addMouseListener(new Main()); So I had two copies of the boolean... I changed it to static, it works like a charm now, thanks! – SomeDude123 Jun 21 '17 at 21:49
  • Oh, not JavaFx, Sorry. It's probably the same idea for awt and/or Swing. – SedJ601 Jun 21 '17 at 21:49
  • You need to to store that flag somewhere else if you want to use it across different instances. Maybe in a different variable outside of that listener class(you would need to take care of synchronization obviously) – Kaushal Niraula Jun 21 '17 at 21:53
  • Just use MouseEvent.getModifiers. – Jeffrey Bosboom Jun 21 '17 at 21:54

0 Answers0