Click sensitivity in Swing

November 2nd, 2012 in Java | , , ,

In our latest application we found that users complain about the sensitivity on minor mouse vibrations during clicking on components. I also found that using a pen tablet it is almost impossible to keep it steady enough for a click to be registered.

Instead a small change in mouse X, Y will cause a mouseDragged notification instead of a mouseClicked.

The solution is to add a function that will check for a tolerance and, if within, cause a click to be executed instead.

In the MouseListener class we add this:

 Java |  copy code |? 
class ToleranceMouseListener implements MouseMotionListener, MouseListener {
	// Our tolerance in both x and y direction
	private static int CLICK_TOLERANCE = 5;
	// The point where we pressed the mouse button down
	private Point startPoint;
	// Method for checking the tolerance 
	private boolean checkDragTolerance(Point e) {
		if (startPoint != null) {
			float changesx = Math.abs(e.x - startPoint.x);
			float changesy = Math.abs(e.y - startPoint.y);
			return (changesx < CLICK_TOLERANCE && changesy < CLICK_TOLERANCE);
		return false;
	// Store where we pressed the mouse button down
	public void mousePressed(MouseEvent e) {
		startPoint = e.getPoint();
	// The magic happens as we release the mouse button
	public void mouseReleased(MouseEvent e) {
		/** Creates a small buffer for what is considered a mouse press vs mouse drag */
		if (checkDragTolerance(e.getPoint())) {
			System.out.println("Redirect click");
		// Code for mouse dragged here, if any
	// Plus empty methods

Leave a Reply