Drawing with a mouse, mouse motion listeners

A mouse listener monitors where the mouse was clicked in the panel. A mouse motion listener monitors where the mouse moved. With that information, the program can allow its user to draw on a panel by clicking and dragging the mouse.

Updating crop X and Y fields, based on where the mouse was clicked

Next, we will add code so the program user can use the mouse to draw a box around the area to be cropped.

  1. Add two private integer instance variables called startX and startY, each initialized to 0.
  private int cropW = 0;
  private int cropH = 0;
  private int startX = 0;
  private int startY = 0;

When the mouse button is pressed down, get the mouse’s x and y coordinates.

  1. In the constructor, add a mouse listener with a mousePressed() method. Use JPanel’s addMouseListener() method, with a new MouseAdapter object as the parameter value. In the MouseAdapter, add a public method called mousePressed()mousePressed() should have one parameter, a MouseEvent called e, and return nothing.
  2. In mousePressed():
    • Create integers x and y, initialized to the x and y location values of e, respectively using MouseEvent’s getX() and getY() methods.
    • Call imageClicked(), passing it x and y as parameter values.

Note: Do not execute the code yet. It will have a syntax error because imageClicked() does not exist yet.

  public ImagePanel(ImageResizer imageResizer) {
    this.imageResizer = imageResizer;
    addMouseListener(new _______________() {
      ______________ mousePressed(____________) {
        ______ x = e.________;
        ______ y = e.________;

Get hands-on with 1200+ tech skills courses.