1

I'm trying to create a buffered image from the contents of a JScrollpane. The Jscrollpane dimesions are 250x200. The contents spillover and only the visible section gets captured in the image. I'm using Java graphics 2D.

Is there a way to capture the complete contents of the scrollpage?

Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689
user907737
  • 71
  • 2

1 Answers1

2

Just paint the contents to the BufferedImage, and not the scroll pane.

For example:

public class Test {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                final Image image = 
                            new ImageIcon("stackoverflow.png").getImage();
                JPanel imagePanel = new JPanel() {
                    @Override
                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        g.drawImage(image, 0, 0, this);
                    }
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(image.getWidth(this),
                                             image.getHeight(this));
                    }
                };
                JScrollPane pane = new JScrollPane(imagePanel); 
                pane.setPreferredSize(new Dimension(200, 200));
                JOptionPane.showMessageDialog(null, pane);

                BufferedImage newImage = getImageFromComponent(imagePanel);
                JLabel label = new JLabel(new ImageIcon(newImage));
                JOptionPane.showMessageDialog(null, label);
            }
        });
    }
    private static BufferedImage getImageFromComponent(Component component) {
        BufferedImage img = new BufferedImage(
                component.getWidth(), component.getHeight(), 
                BufferedImage.TYPE_INT_RGB);
        Graphics g = img.createGraphics();
        component.paint(g);
        g.setFont(new Font("impact", Font.PLAIN, 30));
        g.drawString("Image of Panel", 40, 50);
        g.dispose();
        return img;
    }
}

First the panel is put inside scroll pane.

enter image description here

When we close it, the contents of the panel are drawn to to a BufferedImage, and added to a label.

enter image description here

Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689