I have a JScrollPane m_jScrollPane
with a JLabel m_jlImage
being displayed inside of it. The m_jlImage
is a screen capture with a red dot drawn where the user last clicked on the screen. I wish to move (read scroll) the viewing area of the m_jScrollPane
over the red dot on the m_jlImage
. lastClick
is the last place the user clicked and is in the same coordinates as m_jlImage
.
This is proving to be more difficult that I thought.
I decided to get the ratio of the click point's value to the entire length of the screen along the same axis, and scroll the corresponding scroll bar by that same ratio of its maximum. This seems to only work if the point last clicked on the screen is in the upper left hand corner.
I am not sure how to handle the situation when the clicked point is on the edge of the screen. This scenario produces a ratio, causing the scroll bar to scroll by the same ratio, but the red dot is scrolled out of view because it is on the edge of the screen. Any suggestions on how could I over come this?
public void scrollViewToLastClick()
{
int clckH = lastClick.y;
int clckW = lastClick.x;
int picH = this.m_jlImage.getHeight();
int picW = this.m_jlImage.getWidth();
int ratW = (int)(m_jScrollPane.getWidth()*(double)clckW/(double)picW);
int ratH = (int)(m_jScrollPane.getHeight()*(double)clckH/(double)picH);
m_jScrollPane.getHorizontalScrollBar().setValue(ratW);
m_jScrollPane.getVerticalScrollBar().setValue(ratH);
}
This is a pretty basic example. It uses a image file and places it within a scrollpane (in a round about way).
From there, it simply uses a Swing
Timer
to randomly generate points (within the bounds of the image).Each time a new point is generated, I simply use
scrollToRectVisible
, passing it the location and the size of the point I want to render. This will ensure that the new point (and the dot) is visible within the scroll pane.Now, if you want to display the point as close to the centre as possible, that will require additional work...
Now, if you really want to have fun, set the delay to something like 50 - 100 milliseconds ;)