如何在同一時間使用MouseListener和KeyListener?MouseListener和KeyListener同時使用
例如,如何做這樣的事情
public void keyPressed(KeyEvent e){
// If the mouse button is clicked while any key is held down, print the key
}
如何在同一時間使用MouseListener和KeyListener?MouseListener和KeyListener同時使用
例如,如何做這樣的事情
public void keyPressed(KeyEvent e){
// If the mouse button is clicked while any key is held down, print the key
}
嘗試創建一個布爾isKeyPressed
。在keyPressed
中,將其設置爲true,並在keyReleased
中將其設置爲false。然後,當點擊鼠標時,首先檢查isKeyPressed是否爲true。
使用布爾值來判斷是否按住鼠標按鈕,然後在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變量。
你可以嘗試檢查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");
}
哪像我剛剛發現,產生其他鼠標按鈕的結果...
:如果你有時間爲什麼按位應該是!你能解釋我你的代碼!= 0 .. btw應該是'BUTTON1_DOWN_MASK'? – nachokk
@nachokk不,我試過'BUTTON1_DOWN_MASK',但Java堅持使用過時的'BUTTON1_DOWN' – MadProgrammer
和'mods&KeyEvent.BUTTON1_MASK!= 0'這是什麼意思? – nachokk
*「我如何在同一時間使用MouseListener和KeyListener?」*您爲什麼要處理? Swing通常使用鍵綁定而不是較低級別的'KeyListener',並且'ActionListener'有時候會更好地替代'MouseListener'。這是什麼意圖支持? –