通过拖动鼠标进行Java Swing滚动

时间:2013-05-04 19:25:49

标签: java swing scroll mouse jscrollpane

我正在尝试创建一个手动滚动条,当您将鼠标拖过JPanel时会滚动。到目前为止,我无法改变观点。这是我的代码:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class HandScroller extends JFrame {

    public static void main(String[] args) {
        new HandScroller();
    }

    public HandScroller() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);


        final JPanel background = new JPanel();
        background.add(new JLabel("Hand"));
        background.add(new JLabel("Scroller"));
        background.add(new JLabel("Test"));
        background.add(new JLabel("Click"));
        background.add(new JLabel("To"));
        background.add(new JLabel("Scroll"));

        final JScrollPane scrollPane = new JScrollPane(background);

        MouseAdapter mouseAdapter = new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JViewport viewPort = scrollPane.getViewport();
                Point vpp = viewPort.getViewPosition();
                vpp.translate(10, 10);
                background.scrollRectToVisible(new Rectangle(vpp, viewPort.getSize()));
            }
        };

        scrollPane.getViewport().addMouseListener(mouseAdapter);
        scrollPane.getViewport().addMouseMotionListener(mouseAdapter);

        setContentPane(scrollPane);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

}

我认为这会在x和y方向上将视图移动10,但它根本没有做任何事情。还有什么我应该做的吗?

感谢。

3 个答案:

答案 0 :(得分:2)

您的代码确实有效。简单地说,没有什么可以滚动,因为窗口足够大(实际上,pack()导致JFrame调整大小to fit the preferred size and layouts of its subcomponents

删除pack();并将该行替换为setSize(60,100);以查看效果。

答案 1 :(得分:2)

我认为您可以使用此代码向所有方向移动视图

public void mouseDragged(MouseEvent e) {

           JViewport viewPort = scroll.getViewport();
           Point vpp = viewPort.getViewPosition();
           vpp.translate(mouseStartX-e.getX(), mouseStartY-e.getY());
           scrollRectToVisible(new Rectangle(vpp, viewPort.getSize()));

}

public void mousePressed(MouseEvent e) {

    mouseStartX = e.getX();
    mouseStartY = e.getY();

}

答案 2 :(得分:1)

它正在发挥作用。但是,当您运行此代码时,JScrollPane会变得足够大以适合您的所有项目。添加(例如)

scrollPane.setPreferredSize(new Dimension(50, 50));

你会看到你的鼠标事件正常。