通过拖动鼠标进行Java Swing滚动 [英] Java Swing Scrolling By Dragging the Mouse

查看:211
本文介绍了通过拖动鼠标进行Java Swing滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

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

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?

谢谢.

推荐答案

您的代码确实有效.简而言之,没有什么可滚动的,因为窗口足够大(实际上,pack()导致JFrame调整了

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)

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

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

这篇关于通过拖动鼠标进行Java Swing滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆