If you want the user to be able to "click-and-drag" to select a rectangle you need to implement a MouseMotionListener
. Have a look at the mouseDragged
method:
void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
When you need to get hold of the sub-image, you simply use
public BufferedImage getSubimage(int x, int y, int w, int h)
Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.
If you want to save the resulting image to disk, I suggest you have a look at Saving a Generated Graphic to a PNG or JPEG File.