In this course, we display only a small part of playfield from the previous example and we make able the scrolling inside using the mouse.
Drag with the mouse to move the visible area.
We choose a small visible part without scale relation between its size and the size of the playfield. Here, the visible part size is 10 tiles horizontally and 5 tiles vertically.
First thing to know is to not use a Layout Manager for the container of the playfield, because it uses the preferred size of its components.
This explanation is only true when the playfield use a SpriteDisplayManager. Of course, we can not guarantee anything with another DisplayManager.
How does it work?
You have to remember the 3 magic words:
Preferred size
Size
Offset
Preferred size
The real size of the playfield.
Size
The size of the visible part of the playfield.
Offset
The top left corner coordinates of the visible part of the playfield. This is used even if the size and the preferred size have the same value (for example: you can shake easily the playfield).
Now the example
We explain now how to manipulate the scrolling; the source code is from the file ScrollingPathFinder.java
Initialization of the playfield
We have 4 things to do:
Set the LayoutManger of the container to null
Creates the playfield with its preferred size
Set the size of the playfield
Set the size of the container
This is done by:
...// Creates the playfieldSpriteCollisionManagercollisionManager=newSpriteCollisionManager(10);playfield=newPlayField(collisionManager,10*Tiles.tileSize,5*Tiles.tileSize);playfield.setPreferredSize(Tiles.tiles[0].length*Tiles.tileSize,Tiles.tiles.length*Tiles.tileSize);...setSize(10*Tiles.tileSize,5*Tiles.tileSize);...
Scrolling the visible part
The only thing to do is to set the offset value to another one when we want to scroll. This is done by the method setOffset(int, int) of the playfield.
Here is the source code of the MouseMotionListener and the MouseListener used to scroll the visible part of the playfield: