我知道这已经很老了,但这是一个简单的解决方案,您可以使用它为组件及其边界内的所有组件创建鼠标侦听器(无需单独将侦听器添加到所有组件):
/**
* Creates an {@link AWTEventListener} that will call the given listener if
* the {@link MouseEvent} occurred inside the given component, one of its
* children or the children's children etc. (recursive).
*
* @param component
* the component the {@link MouseEvent} has to occur inside
* @param listener
* the listener to be called if that is the case
*/
public static void addRecursiveMouseListener(final Component component, final MouseListener listener) {
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
@Override
public void eventDispatched(AWTEvent event) {
if(event instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) event;
if(mouseEvent.getComponent().isShowing() && component.isShowing()){
if (containsScreenLocation(component, mouseEvent.getLocationOnScreen())) {
if(event.getID() == MouseEvent.MOUSE_PRESSED) {
listener.mousePressed(mouseEvent);
}
if(event.getID() == MouseEvent.MOUSE_RELEASED) {
listener.mouseReleased(mouseEvent);
}
if(event.getID() == MouseEvent.MOUSE_ENTERED) {
listener.mouseEntered(mouseEvent);
}
if(event.getID() == MouseEvent.MOUSE_EXITED) {
listener.mouseExited(mouseEvent);
}
if(event.getID() == MouseEvent.MOUSE_CLICKED){
listener.mouseClicked(mouseEvent);
}
}
}
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
/**
* Checks if the given location (relative to the screen) is inside the given component
* @param component the component to check with
* @param screenLocation the location, relative to the screen
* @return true if it is inside the component, false otherwise
*/
public static boolean containsScreenLocation(Component component, Point screenLocation){
Point compLocation = component.getLocationOnScreen();
Dimension compSize = component.getSize();
int relativeX = screenLocation.x - compLocation.x;
int relativeY = screenLocation.y - compLocation.y;
return (relativeX >= 0 && relativeX < compSize.width && relativeY >= 0 && relativeY < compSize.height);
}
注意:一旦鼠标退出此侦听器的根组件,mouseExited(mouseEvent)
可能不会触发,但是您可以将鼠标侦听器添加到根组件本身,它应该会触发。
mouseExited(mouseEvent)
虽然一般来说是不可靠的。