简体   繁体   中英

Simultaneous/Combined MouseListener & KeyListener, MouseEvent & KeyEvent Java

I want to know how work Simultaneously a MouseEvent & KeyEvent .

Suppose an JFrame, JPanel.

I want to know how work with an Event when certain MouseEvent & KeyEvent example:

addKeyListener(new KeyAdapter() {
  @Override public void keyReleased( KeyEvent evt) {
    if ((evt.getKeyCode() == KeyEvent.VK_META) || (evt.getKeyCode() == KeyEvent.VK_WINDOWS)) {
      //SomeEVENT
    }
  }
});

addMouseListener(new MouseAdapter() {
  public void mouseReleased(MouseEvent evt) {
    if (SwingUtilities.isLeftMouseButton(evt)) {
      System.out.println("Left button released.");
    }
  }
});

TEST CODE :

addMouseListener(new MouseAdapter() {

  public void mouseClicked(MouseEvent evt) {
    System.out.println("mouseClicked:");
    if ((evt.getModifiers() & KeyEvent.VK_META) == KeyEvent.VK_META) {
      System.out.println("KeyEvent.VK_META:");
    }
    if ((evt.getModifiers() & KeyEvent.VK_CONTROL) == KeyEvent.VK_CONTROL) {
      System.out.println("KeyEvent.VK_CONTROL:");
    }
    System.out.println("KeyEvent.getKeyModifiersText(evt.getModifiers()):" 
        + KeyEvent.getKeyModifiersText(evt.getModifiers()));

  }
});

Output

mouseClicked:
mouseClicked:
mouseClicked:
mouseClicked:
mouseClicked:

The problem the Button Control is not detected!!!

But How perform the action only when simultaneosly LeftButton + CMD or WIN ?

EDIT2

Using my before TEST CODE and Pressing the Shift + Click, the Message is shown!!!

mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⌥+Button1
mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⌘+Button1
mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⌃+Button1
mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⌘+⌥+Button1
mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⌘+⌥+Button1
mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⌥+Button1
mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⌘+⌥+Button1
mouseClicked:
KeyEvent.getKeyModifiersText(evt.getModifiers()):Button1
mouseClicked:
KeyEvent.VK_CONTROL:
KeyEvent.getKeyModifiersText(evt.getModifiers()):⇧+Button1

Is it a OS Problem (I have macOS Sierra )?

The answer is a simple as reading the JavaDocs for MouseEvent

The MouseEvent carries with it an Extended Modifier state which is a simple bit mask of the buttons and keys which were used to generate the event. There are plenty of examples about of how to make use of them.

Because I'm both stupid and lazy, I just prefer to use the functionality provided by the event object itself, like MouseEvent#isControlDown and MouseEvent#isMetaDown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM