繁体   English   中英

拖动对象时自动滚动JScrollpane

[英]Autoscroll a JScrollpane when dragging an object

我创建了一个约会日历,该日历本质上是一个JPanel,其中包含其他所有可移动且可调整大小的JPanel,所有这些JPanel都被JScrollpane包围,这一切都很好,并且我可以使用滚动条正确地滚动JPanel。 我即将完成我的申请,但想再做一件事。

我想做的是当用户移动约会(JPanel)时,当您到达滚动窗格的边缘时,它将自动以所需的速度滚动。 我很困惑哪个现有的方法或类可以做到这一点(如果有的话),或者是否有人知道有一个适合我需要的jar库?

那是懒惰吗? 是的,我想我应该自己编写代码,如果您同意,有人可以建议我从哪里开始? 我仍在学习Java,可能需要轻轻推一下才能保持代码整洁。

如果我可以提供更多详细信息来帮助您解答,请告诉我。

好的,实际上并不复杂。 您需要调用setAutoscroll(true); 在“ scrollable”组件上,并添加一个调用scrollRectToVisibleMouseMotionListener

这是一个小的示例代码:

import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class TestImageResize {

    protected void initUI() throws MalformedURLException, IOException {
        final JFrame frame = new JFrame(TestImageResize.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        BufferedImage bi = ImageIO.read(new URL(
                "http://www.desktopwallpaperhd.net/wallpapers/19/5/islands-paradise-maldive-nature-background-image-landscape-194469.jpg"));
        JPanel panel = new JPanel(new BorderLayout());
        JLabel label = new JLabel(new ImageIcon(bi));
        panel.add(label);
        MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
                ((JPanel) e.getSource()).scrollRectToVisible(r);
            }
        };
        panel.addMouseMotionListener(doScrollRectToVisible);

        panel.setAutoscrolls(true);
        frame.add(new JScrollPane(panel));
        frame.pack();
        frame.setSize(frame.getWidth() / 2, frame.getHeight() / 2);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new TestImageResize().initUI();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM