Search code examples
javaswingscrolljpaneljscrollpane

Simple way of scrolling over a certain rectangle with a JScrollPane and a JPanel (custom)


I have created a custom JPanel class called ImagePanel. I override the paintComponent method like this...

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawImage(image, 0,0, null);

}

The purpose of the custom panel is to simply draw an image.

In my JFrame, I create a ScollPane that is added to the JFrame. When I created the ScrollPane though, I pass in the instance of my imagePanel, like this...

ip = new ImagePanel();
JScrollPane jsp = new JScrollPane(ip);
this.add(jsp);

Now all I want as an easy to use way of using the scroll bars to scroll over my image. Right now the image is very large and scrollbars do not appear. I use the policy to make them visible, but the handles to the scrollbars are not there.

Does anyone know an easy way to do this?


Solution

  • Try with JPanel#setPreferredSize() that will force the JScrollPane to show the scroll bar if needed.

    public void paintComponent(Graphics g)
    {
       super.paintComponent(g);
       g.drawImage(image, 0,0, null);
       // set the size of the panel based on image size
       setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    }
    

    EDIT

    Setting setPreferredSize() inside overridden paintComponent() is not a good way.

    You can do it in a simpler way using JLabel as suggested by @mKorbel. For more info have a look at the comments below.

    BufferedImage image = ...
    JLabel label = new JLabel(new ImageIcon(image)); // set the icon
    
    JScrollPane jsp = new JScrollPane(label);
    

    Screenshot:

    enter image description here