[英]MouseListener and KeyListener used at the same time
如何同時使用MouseListener和KeyListener?
例如,如何做這樣的事情
public void keyPressed( KeyEvent e){
// If the mouse button is clicked while any key is held down, print the key
}
使用布爾值表示是否按住了鼠標按鈕,然后在MouseListener中更新該變量。
boolean buttonDown = false;
public class ExampleListener implements MouseListener {
public void mousePressed(MouseEvent e) {
buttonDown = true;
}
public void mouseReleased(MouseEvent e) {
buttonDown = false;
}
//Other implemented methods unimportant to this post...
}
然后,在KeyListener類中,只需測試buttonDown變量。
嘗試創建一個布爾值isKeyPressed
。 在keyPressed
中將其設置為true,在keyReleased
中將其設置為false。 然后,當單擊鼠標時,首先檢查isKeyPressed是否為true。
您可以嘗試檢查KeyEvent
修飾符的狀態,例如...
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int mods = e.getModifiers();
System.out.println(mods);
if ((mods & KeyEvent.BUTTON1_MASK) != 0) {
System.out.println("Button1 down");
}
}
});
我還應該指出,你可以...
int ext = e.getModifiersEx();
if ((ext & KeyEvent.BUTTON1_DOWN_MASK) != 0) {
System.out.println("Button1_down_mask");
}
正如我剛剛發現的那樣,它會為其他鼠標按鈕產生結果...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.