Crop the Image with the Mouse
Learn to crop the image with mouse drag and add code to select the text of the text field when clicked.
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.
- Add two private integer instance variables called
startX
andstartY
, each initialized to0
.
...
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.
- In the constructor, add a mouse listener with a
mousePressed()
method. Use JPanel’saddMouseListener()
method, with a newMouseAdapter
object as the parameter value. In theMouseAdapter
, add a public method calledmousePressed()
.mousePressed()
should have one parameter, aMouseEvent
callede
, and return nothing. - In
mousePressed()
:- Create integers
x
andy
, initialized to thex
andy
location values ofe
, respectively using MouseEvent’sgetX()
andgetY()
methods. - Call
imageClicked()
, passing itx
andy
as parameter values.
- Create integers
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.________;
imageClicked(________);
}
});
}
...
Get hands-on with 1200+ tech skills courses.