简体   繁体   中英

Java Swing Scrolling By Dragging the Mouse

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.

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.

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

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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