我正在使用JScrollPane來包含大型JPanel。當鼠標不在JScrollPane的範圍內時,我希望它在該方向上滾動。例如,如果JScrollPane的頂部位於(100,100),並且鼠標位於組件的頂部之上,我希望它向上滾動。如何使用JScrollPane連續滾動
到目前爲止,我發現這一點:
private Point origin;
在構造
...
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
origin = new Point(e.getPoint());
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
if (origin != null) {
JViewport viewPort = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, Assets.adder.viewer);
if (viewPort != null) {
Rectangle view = viewPort.getViewRect();
if (e.getX() < view.x) view.x -= 2;
if (e.getY() < view.y) view.y -= 2;
if (view.x < 0) view.x = 0;
if (view.y < 0) view.y = 0;
if (e.getX() > view.x + view.getWidth()) view.x += 2;
if (e.getY() > view.y + view.getHeight()) view.y += 2;
scrollRectToVisible(view);
}
}
}
});
這個工作,但是當鼠標在運動中它才能正常運行,否則就沒有。如何在鼠標位於JScrollPane之外時使其工作,但也不會移動?
如何使用定時器(例如每100ms)獲取鼠標位置並使用它進行計算? – Phiwa
類似[this](http://stackoverflow.com/questions/15604399/simple-way-of-creating-an-animated-jscrollpane-in-java/15605803#15605803)或[this](http:// stackoverflow.com/questions/33907207/how-to-make-jscrollpane-in-borderlayout-containing-jpanel-smoothly-autoscroll/33907401#33907401)可能會幫助 – MadProgrammer