如何使用 JScrollPane 连续滚动
How to continuously scroll with JScrollPane
我正在使用 JScrollPane 来包含一个大的 JPanel。当鼠标不在 JScrollPane 的范围内时,我希望它向那个方向滚动。例如,如果 JScrollPane 的顶部位于 (100, 100) 并且鼠标位于组件顶部上方,我希望它向上滚动。
到目前为止我发现了这个:
private Point origin;
在构造函数中...
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
origin = new Point(e.getPoint());
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
if (origin != null) {
JViewport viewPort = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, Assets.adder.viewer);
if (viewPort != null) {
Rectangle view = viewPort.getViewRect();
if (e.getX() < view.x) view.x -= 2;
if (e.getY() < view.y) view.y -= 2;
if (view.x < 0) view.x = 0;
if (view.y < 0) view.y = 0;
if (e.getX() > view.x + view.getWidth()) view.x += 2;
if (e.getY() > view.y + view.getHeight()) view.y += 2;
scrollRectToVisible(view);
}
}
}
});
这个可以,但是只有鼠标在运动的时候才可以,否则就不行。当鼠标在 JScrollPane 之外但又不动时,如何让它工作?
查看 JComponent class 的 setAutoScrolls(...)
方法。
您可以只使用:
panel.setAutoScrolls( true );
然后你使用下面的MouseMotionListener
:
MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
((JPanel)e.getSource()).scrollRectToVisible(r);
}
};
panel.addMouseMotionListener(doScrollRectToVisible);
此概念在 How to Use Scroll Panes 上的 Swing 教程中的 ScollDemo
示例中进行了演示。
我正在使用 JScrollPane 来包含一个大的 JPanel。当鼠标不在 JScrollPane 的范围内时,我希望它向那个方向滚动。例如,如果 JScrollPane 的顶部位于 (100, 100) 并且鼠标位于组件顶部上方,我希望它向上滚动。
到目前为止我发现了这个:
private Point origin;
在构造函数中...
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
origin = new Point(e.getPoint());
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
if (origin != null) {
JViewport viewPort = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, Assets.adder.viewer);
if (viewPort != null) {
Rectangle view = viewPort.getViewRect();
if (e.getX() < view.x) view.x -= 2;
if (e.getY() < view.y) view.y -= 2;
if (view.x < 0) view.x = 0;
if (view.y < 0) view.y = 0;
if (e.getX() > view.x + view.getWidth()) view.x += 2;
if (e.getY() > view.y + view.getHeight()) view.y += 2;
scrollRectToVisible(view);
}
}
}
});
这个可以,但是只有鼠标在运动的时候才可以,否则就不行。当鼠标在 JScrollPane 之外但又不动时,如何让它工作?
查看 JComponent class 的 setAutoScrolls(...)
方法。
您可以只使用:
panel.setAutoScrolls( true );
然后你使用下面的MouseMotionListener
:
MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
((JPanel)e.getSource()).scrollRectToVisible(r);
}
};
panel.addMouseMotionListener(doScrollRectToVisible);
此概念在 How to Use Scroll Panes 上的 Swing 教程中的 ScollDemo
示例中进行了演示。