Wednesday, July 18, 2012

Handling mouse clicks on UI components

It seems to be common practice to override 'mouseClicked' when adding mouse functionality to custom components. It's a bad idea to do so from a user experience perspective, because the mouse has to be pressed and released at the exact same position for the event to be fired. It's likely for the user to accidentally move the mouse by at least one pixel while clicking.

A very simple way to counter this is to override 'mouseReleased' instead, however you would also have to check that the mouse is currently on the source component, otherwise releasing outside of the source component's bounds would allow qualify as a valid click.

Here's how:

    private class ClickListener extends MouseAdapter {

        public void onMouseClick(Component src, MouseEvent e) {
            // handle click event for component
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            Component src = (Component) e.getSource();
            if (src.contains(e.getPoint())) {
                onMouseClick(src, e);
            }
        }
    }

No comments:

Post a Comment