【问题标题】:How to continuously scroll with JScrollPane如何使用 JScrollPane 连续滚动
【发布时间】:2016-04-30 10:35:09
【问题描述】:

我正在使用 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 之外,但也不移动时,如何使它工作?

【问题讨论】:

  • 如何使用计时器(例如每 100 毫秒)获取鼠标位置并用它计算?
  • thisthis 之类的内容可能会有所帮助

标签: java swing scroll jscrollpane


【解决方案1】:

查看 JComponent 类的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 示例中得到了演示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多