简体   繁体   中英

How do I capture the contents of a Scrollpane using graphics

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?

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.

在此处输入图片说明

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM