繁体   English   中英

如何使用图形捕获滚动面板的内容

[英]How do I capture the contents of a Scrollpane using graphics

我正在尝试从JScrollpane的内容创建一个缓冲的图像。 Jscrollpane尺寸为250x200。 内容溢出,图像中仅捕获可见部分。 我正在使用Java图形2D。

有没有办法捕获滚动页面的完整内容?

只需将内容绘制到BufferedImage上,而不是滚动窗格上即可

例如:

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;
    }
}

首先,将面板放在滚动窗格中。

在此处输入图片说明

当我们关闭它时,面板的内容被绘制到BufferedImage,并添加到标签。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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