Search code examples
javaswingjframejpaneljscrollpane

Java Swing: JScrollPane doesn't work with Buffered Image in a JPanel


This is my JFrame class which should display an image which has a height and width of 2000px. The displayed area should only have a width and height of 800px and I want to be able to use the scrollbar to reach the rest of the 2000px. But currently there is only the 800x800 pixel Frame and I can't scroll the picture. I can see the scrollbar but I can't scroll it. I only can see more of the picture if I drag the window larger.

What my code is doing right now: creating the instance panel of the Panel class which displays an image with height: 2000px and width: 2000px. Then I create a JScrollPane and pass the panel instance.

If I don't use the lines setHorizontalScrollBarPolicy, setVerticalScrollBarPolicyI don't even see a scrollbar. If I use these two lines I see a scrollbar for horizontal and vertical scrolling but I can't use them because it seems like the picture is maximized.

This is my Frame class:

public class Frame extends JFrame {


    public Frame() {

        Panel panel = new Panel();
       
        JScrollPane scrollPane = new JScrollPane(panel);

        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);


        add(scrollPane);
       
        this.getContentPane().setPreferredSize(new Dimension(800, 800));
        panel.generateImage();
        setVisible(true);

        pack();
    }

And this is the class where the Image gets generated

public class Panel extends JPanel {

   
    private BufferedImage img;

    public Panel() {
     
        img= new BufferedImage(2000, 2000, BufferedImage.TYPE_INT_RGB);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawImage(img, 0, 0, null);
    }

public void generateImage () {

       //...image gets generated here
        repaint();
    }
}

this is an example what it looks like right now. The dog is just an example but it hopefully makes my problem more clearly-> I want to scroll through the image so that I can see other parts of the dog.

enter image description here


Solution

  • You may be forgetting the panel's preferred size, since this is what is used to expand the JPanel "view" that is held within a JScrollPane's view-port. Consider overriding getPreferredSize in the drawing JPanel by doing something like:

    @Override
    public Dimension getPreferredSize() {
        if (img == null) {
            return super.getPreferredSize();
        } else {
            int w = img.getWidth();
            int h = img.getHeight();
            return new Dimension(w, h);
        }
    }
    

    Of course, you must import java.awt.Dimension