I am making a map editor for a game I am working on. There is a JPanel in the JScrollPane that displays the map to be edited. What I would like to do is make it that when the user is holding down the Spacebar and dragging their mouse in the JPanel, the JScrollPanel will scroll along with the dragging. Here is what I have so far:
panelMapPanel.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseDragged(MouseEvent e) {
//Gets difference in distance x and y from last time this listener was called
int deltaX = mouseX - e.getX();
int deltaY = mouseY - e.getY();
mouseX = e.getX();
mouseY = e.getY();
if(spacePressed){
//Scroll the scrollpane according to the distance travelled
scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getValue() + deltaY);
scrollPane.getHorizontalScrollBar().setValue(scrollPane.getHorizontalScrollBar().getValue() + deltaX);
}
}
});
Currently it works but the scrolling is not smooth at all. Moving the mouse a lot at a time is fine but doing small drags makes the scrollpane go berserk.
Any ideas how to improve this?
For those who enjoy a visual to help, here is the editor:
Addition Notes (Edit):
- I have tried
scrollPane.getViewport().setViewPosition(new Point(scrollPane.getViewport().getViewPosition().x + deltaX, scrollPane.getViewport().getViewPosition().y + deltaY));
- The dragging is more fidgety when moving the mouse slowly, while big movements are more smooth
- I tried using scrollRectToVisible without luck
JViewport
's viewable area or position – ChitterJViewport#setViewPosition
would be a good start, but remember, this is the top/left corner of the viewable area. You might also have a look at the methods thatJScrollPane
provides or even just useJCompoint#scrollRectToVisible
– ChitterscrollRectToVisible
and call it on the component where theMouseListener
is installed, just remember, you will need to calculate the offset from the top/left point and the mouse point – ChitterscrollPane.scrollRectToVisible(scrollPane.getViewport().getViewRect());
andpanelMapPanel.scrollRectToVisible(scrollPane.getViewport().getViewRect());
, they both have the same result as before. By the waypanelMapPanel
is the name of the JPanel that I draw the map image onto. – PresentableMouseMoitionListener
seeing the viewport position change as a drag event of some kind ... which accounts for the flickering ... – Chitter