@Override
public void mousePressed(MouseEvent e) {
//do some stuff
}
/*Override other methods*/
});
或者最好使用 `MouseAdapter` ```
btn.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
//do some stuff
}
/*No need to override other methods, `MouseAdapter` already does it*/
});
b.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
doOnPressedAction();
}
public void mouseReleased(MouseEvent e) {
doOnReleasedAction();
}
});
b.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if (sendButton.getModel().isPressed()) {
doOnPressedAction();
} else {
// just in case it can happen that the button is released on
// a key press action (maybe another controls key listener...)
doOnReleasedAction();
}
}
public void keyReleased(KeyEvent e) {
doOnReleasedAction();
}
});
2条答案
按热度按时间brc7rcf01#
点击意味着一个按钮被按下和释放。单击按钮时触发单击事件,并且仅当释放鼠标时按钮仍处于待命状态(鼠标位于按钮的边界内)。要处理pressed事件,请使用低级
MouseListener
```btn.addMouseListener(new MouseListener() {
});
00jrzges2#
上面的答案只对鼠标事件有React,但当有输入焦点时,可以使用空格键切换按钮按下的状态。对于完整的实现,请使用mouselistener和keylistener。