title: Toggling a boolean with KeyListeners and MouseListeners
body: <p>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. </p>
  
  <p>Here is keyListener the code: </p>
  
  <pre><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);
          }
      }
  </code></pre>
  
  <p>and the MouseListener code: </p>
  
  <pre><code>@Override
      public void mouseClicked(MouseEvent e) {
  
          int keyCode = e.getButton();
  
          if(keyCode == MouseEvent.BUTTON1){
              System.out.println("MOUSE button 1 pressed. ALT: "+altPressed);
  
          }
  
      }
  </code></pre>
  
  <p>Console output (with some commentary)</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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!  </p>