Java Swing Scrolling By Dragging the Mouse

2019-09-14 16:59发布

问题:

I am trying to create a hand scroller that will scroll as you drag your mouse across a JPanel. So far I cannot get the view to change. Here is my code:

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);
    }

}

I would think that this would move the view by 10 in the x and y directions, but it is not doing anything at all. Is there something more that I should be doing?

Thanks.

回答1:

Your code does work. Simply, there is nothing to scroll, as the window is large enough (actually, pack() has caused the JFrame to resize to fit the preferred size and layouts of its subcomponents)

Remove pack(); and replace that line with, say, setSize(60,100); to see the effect.



回答2:

I think so you can move the view in all directions with this code

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();

}


回答3:

It is working. However, when you run this code, the JScrollPane is made large enough to fit all your items. Add (for instance)

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

and you'll see that your mouse events work fine.