Java Swing Scrolling By Dragging the Mouse

社会主义新天地 提交于 2019-12-13 06:16:06

问题


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.



来源:https://stackoverflow.com/questions/16378109/java-swing-scrolling-by-dragging-the-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!