JScrollPane with JPanel inside doesn't show scroll bar when picture is bigger
-
03-07-2021 - |
Question
I'm making an utility to define footholds in a map for my game and i am displaying the preview of the map inside a JPanel that's inside a JScrollPane. I would like to be able to scroll when the map is bigger than the JScrollPane. How should i do that?
Here's a picture
The image of the map fits inside of the scrollpane but the image is actually larger so we don't get to see the whole map.
Some code:
The JPanel class which holds the image inside of the scrollPane
public class MapDisplay extends JPanel {
public MapDisplay() {
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(0xDFDFDF));
g2d.fillRect(0, 0, 2000, 2000);
if (mapinfo != null) {
if (mapinfo.img != null) {
g2d.drawImage(mapinfo.img, 0, 0, null);
}
}
repaint();
}
}
the scrollPane's declaration
final JScrollPane scrollPane_1 = new JScrollPane(mapDisplay);
scrollPane_1.setBounds(10, 11, 989, 553);
getContentPane().add(scrollPane_1);
add(scrollPane_1);
Solution
The MapDisplay
has to 'tell' the JScrollPane
how big it wants to be. You can do so by implementing the getPreferredSize
method of MapDisplay
.
public Dimension getPreferredSize() {
return new Dimension(widthOfMap, heightOfMap);
}
Further, do not call repaint()
from inside the paintComponent()
method, as this results in an infinite loop.