I am creating a Java app that will allow users to view images and to pan the image using their mouse. To implement the panning of the image I use a combination of mouseClicked
and mouseDragged
events using JViewports. The bulk of the code is in the mouseDragged method
public void mouseDragged(MouseEvent e, WindowWrapper w) {
final JViewport vp = someFieldViewPort;
//Getting the point that the mouse is dragged to to
Point cp = e.getPoint();
final Point vPoint = vp.getViewPosition();
//I found the image went off the content to show the white border so I included this
// Here pp is a field that I sent when the mouse is clicked in a separate method
if(vPoint.getX()+pp.x-cp.x>=0 & vPoint.getY()+pp.y-cp.y>=0)
vPoint.translate(pp.x-cp.x, pp.y-cp.y);
else if(vPoint.getX()+pp.x-cp.x>=0 & vPoint.getY()+pp.y-cp.y<0)
vPoint.translate(pp.x-cp.x, (int) -vPoint.getY());
else if(vPoint.getX()+pp.x-cp.x<0 & vPoint.getY()+pp.y-cp.y>=0)
vPoint.translate((int) -vPoint.getX(), pp.y-cp.y);
//finally set the position of the viewport
vp.setViewPosition(vPoint);
vp.repaint();
}
While this works I feel that there must be an easier way to do all of this. If not all of it, could the code to prevent the viewport going off the image to the surrounding border be replaced?
Try using
scrollRectToVisible(...)
method instead ofJViewport#setViewPosition(...)
:+1 to @Dans answer.
Here is an example I made, basically uses JPanel with added
MouseAdapter
and overridesmousePressed()
andmouseDragged()
methods.mouseDragged()
method will incrementx
andy
co-ordinates of image accordingly and will be drawn viapaintComponent(...)
ofJPanel
andGraphics2D#drawImage(Image img,int x,int y,ImageObserver io)
.Before click and drag of mouse:
After click and drag of mouse:
I would do it in a different way. I would probably define an object called
Image
or similar. It would define aBufferedImage
and twoint
values:x
andy
.The
Image
object would also have adraw()
method that would just know how to draw an image to aGraphics2D
object at thex, y
location.On mouse events, I would modify the
x
andy
values inside theImage
object and under thepaint
of the component I would callimage.draw(g2)
.