gpt4 book ai didi

Java Swing 通过拖动鼠标滚动

转载 作者:行者123 更新时间:2023-12-01 17:24:06 25 4
gpt4 key购买 nike

我正在尝试创建一个手动滚动器,当您在 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);
}

}

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

谢谢。

最佳答案

我认为您可以使用此代码向各个方向移动 View

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

}

关于Java Swing 通过拖动鼠标滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16378109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com