java在更大的图像上移动视图端口;jlabel+JScrollPane
我有一个JScrollPane m_jScrollPane
,里面显示着一个JLabel m_jlImage
。m_jlImage
是一个屏幕截图,在用户上次单击屏幕的位置绘制了一个红点。我希望将m_jScrollPane
的查看区域移到m_jlImage
上的红点上(阅读滚动)lastClick
是用户最后单击的位置,与m_jlImage
位于同一坐标
事实证明,这比我想象的要困难得多
我决定沿着同一个轴获得点击点的值与整个屏幕长度的比率,并按其最大值的相同比率滚动相应的滚动条。这似乎只适用于屏幕上最后一次点击的点位于左上角的情况
当点击点位于屏幕边缘时,我不确定如何处理这种情况。这种情况会产生一个比率,导致滚动条以相同的比率滚动,但红点会被滚动到屏幕边缘,因此无法查看。有没有关于我该如何克服这一点的建议
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);
}
# 1 楼答案
这是一个非常基本的例子。它使用一个图像文件并将其放置在滚动窗格中(以循环方式)
从那里,它只需使用Swing
Timer
来随机生成点(在图像的边界内)每次生成一个新点时,我只需使用
scrollToRectVisible
,将要渲染的点的位置和大小传递给它。这将确保新点(和点)在滚动窗格中可见现在,如果你想显示尽可能靠近中心的点,这将需要额外的工作
现在,如果你真的想玩得开心,可以将延迟设置为50-100毫秒;)