Skip to content
Advertisement

java – detect mouseReleased without mousePressed

I have a MouseListener on a component and want to listen to mouseReleased events, without needing mousePressed events. How can I detect if the user presses on another button, the desktop, or other window, (or anything, really) and releases on my component?

For instance, in the following example, how can I get it to print “cool”, instead of “Not cool”?

titleBar.addMouseListener(new MouseListener()
{
    @Override public void mouseReleased(MouseEvent e)
    {
        System.out.println("cool");//Detect this
    }
    @Override public void mousePressed(MouseEvent e)
    {
        System.out.print("Not ");//Without this having to happen first
    }
    @Override public void mouseExited(MouseEvent e)
    {
    }
    @Override public void mouseEntered(MouseEvent e)
    {
    }
    @Override public void mouseClicked(MouseEvent e)
    {
    }
});

Advertisement

Answer

You can’t listen for a mouseReleased when the mousePressed originated on another application. This is because the Java application will not have focus when the mouse is released. Java con only handle events when it has focus.

Within a Java application you can listen for all mouseReleased events. However, in this case the mouseReleased event will be generated for the component that generated the mousePressed event. So you will need to also listen for mouseEntered and mouseExited events. So if a mouseReleased event is preceded by a mouseEntered event you would need to use the source of the mouseEntered event to get the object for the mouseReleased event.

For this you can use the AWTEventListener. See Global Event Listeners for more information.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement