How do I get the number of buttons on the mouse?

MouseInfo provides methods for getting information about the mouse, such as mouse pointer location and the number of mouse buttons.

package org.kodejava.awt;

import java.awt.*;

public class MouseNumberOfButtons {
    public static void main(String[] args) {
        // Get the number of buttons on the mouse. On systems without a
        // mouse, returns -1. HeadlessException if
        // GraphicsEnvironment.isHeadless() returns true.
        int numberOfButtons = MouseInfo.getNumberOfButtons();
        System.out.println("Mouse Number Of Buttons = " + numberOfButtons);
    }
}

The output of the code snippet above:

Mouse Number Of Buttons = 5

How do I get the location of mouse pointer?

MouseInfo provides methods for getting information about the mouse, such as mouse pointer location and the number of mouse buttons.

package org.kodejava.awt;

import java.awt.*;

public class MouseInfoDemo {
    public static void main(String[] args) {
        int i = 0;
        while (i < 10) {
            // Get the location of our mouse x and y coordinate using
            // the PointerInfo.getLocation() method which return an 
            // instance of Point.
            Point location = MouseInfo.getPointerInfo().getLocation();
            double x = location.getX();
            double y = location.getY();

            System.out.println("x = " + x);
            System.out.println("y = " + y);

            try {
                Thread.sleep(1000);
                i++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

How do I create mouse event using Robot class?

In this example we are automating the process of creating mouse event using the java.awt.Robot class.

package org.kodejava.awt;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;

public class MovingMouseDemo {
    public static void main(String[] args) {
        try {
            Robot robot = new Robot();

            // Move mouse cursor to 200, 500
            robot.mouseMove(200, 500);

            // Press the mouse button #1.
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

            // Scroll the screen down for a mouse with a wheel support.
            robot.mouseWheel(150);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}