Take the 2-minute tour ×

I have a weird problem viewing a JPEG image by implementing Java Swing Scrollable interface.

My code allows me to draw a rectangle on top of the image using left-mouse button. Everything works ok if I don't touch the scroll bars.

But as soon as I scroll down, a rectangle gets drawn on a different location. Basically if I move the top-down scroll bar, the the image gets drawn with the wrong y-coordinate. Same behavior if scrolling left-right, the image gets drawn with the wrong x-coordinate. These x,y coordinates reporesent the upper-left Point(x,y) to start drawing Rectangle.

So after scrolling down and left-click on image to draw a rectangle the y-coordinate off. Below is an event I added to one of the panels that holds the image stuff.

public void mousePressed(MouseEvent m) {
   if (SwingUtilities.isLeftMouseButton(m)) {
      int y = m.getY(); //This y-coordinate is off whenever I scroll down the image.

Anyone has any clues onto what could be the problem? I mean I'm getting the y-coordinate from the MouseEvent, so I would expect it to have the correct value.


share|improve this question

1 Answer 1

What coordinates are you expecting to get? The values make sense to me: when you scroll down, the y coordinate increases even though you're clicking in the same location on the screen.

The component that is in a scrollpane doesn't know anything about the scrollpane. So when the click occurs, the y coordinate matches where the click would have been if the component was big enough to be entirely visible.

If you want to convert into the coordinate system of the scrollpane, you could do something like this I guess:

public void mouseClicked( MouseEvent e )
  Point p = SwingUtilities.convertPoint( label, e.getX(), e.getY(), scrollPane );
  System.out.println( "Converted: " + p.x + ", " + p.y );

(Edit: Just a note, the code above assumes label is the component that displays the image)

share|improve this answer
Like @Ash, I get image-local coordinates no matter the scroll position; you might check your rectangle drawing in paintComponent(), too. –  trashgod Sep 27 '10 at 23:34
Nope that didn't work but I added a listener to the ScrollBars to get the value every time they are moved and then adding that value to the Point(x,y) of the rectangle being drawn and it worked. Thanks thou you guided me to the correct path to fix this. –  Marquinio Sep 30 '10 at 18:31

Your Answer


