如何在Swing中将面板保存为图像?

14

大家好,我想将包含标签和按钮等组件的面板转换为图像文件。

我已经编写了以下代码。图片已保存,但是面板的内容不可见或未保存。请问有谁能告诉我如何保存带其组件的面板?

代码:

package PanelToImage;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class sample extends JPanel {

public JPanel firstpanel;
public JPanel secondpanel;
JLabel label1, label2;
JButton button1, button2;

public sample() {
    firstpanel = new JPanel();
    firstpanel.setSize(400,300); 
    firstpanel.setBackground(Color.RED);
    secondpanel = new JPanel();
    secondpanel.setBackground(Color.GREEN);
    secondpanel.setSize(400,300); 

    label1 = new JLabel("label1");
    label2 = new JLabel("label2");
    button1 = new JButton("button1");
    button2 = new JButton("button2");

    firstpanel.add(label1);
    firstpanel.add(button1);

    secondpanel.add(label2);
    secondpanel.add(button2);

    saveImage(firstpanel);

    add(firstpanel);

    // add(secondpanel);
}

public static void main(String args[]) {

    JFrame frame = new JFrame();
    sample sam = new sample();
    frame.setContentPane(sam);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);

}

private void saveImage(JPanel panel) {
    BufferedImage img = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
    panel.paint(img.getGraphics());
    try {
        ImageIO.write(img, "png", new File("E://Screen.png"));
        System.out.println("panel saved as image");

    } catch (Exception e) {
        System.out.println("panel not saved" + e.getMessage());
    }
}
}

请参阅 ComponentImageCapture.java 以显示可见的组件 - 向下滚动查看 另请参阅 和 Rob Camick 的一个类,可以省去从未显示的组件中获取图像的大部分繁重工作。在 为什么 JTable 头部不会出现在图片中? 中还可以看到一些其他在显示之前渲染组件的技巧。 - Andrew Thompson
1
在我看来,您提供了错误的“路径”以创建文件。由于您的程序不知道“E驱动器”的内容,因此将创建的新“文件”必须使用相对于“.class文件”的“相对路径”进行引用,例如“....\E:\Screen.png”,使其向上两个级别,然后到达“E驱动器”,类似这样的东西会起作用。使用我的答案或@Alberto的答案创建的图像将与.class文件并排创建。 - nIcE cOw
2个回答

20

这段代码在我的JFrame中可以正常工作:

Container c = getContentPane();
BufferedImage im = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
c.paint(im.getGraphics());
ImageIO.write(im, "PNG", new File("shot.png"));

也许你已经使用过自定义面板了。如果是这样,请尝试在你的面板的paint方法的开头添加super.paint(g)编辑: 你必须在显示框架后调用saveImage
public static void main(String args[]) {
    ...
    frame.setSize(400, 300);
    sam.saveImage(sam.firstpanel);
}

编辑2:这是保存的图片(因为布局而小,但证明它应该可以工作):

enter image description here

我在main函数的最后调用了saveImage函数,并像nIcE cOw所说,使用了用户目录下的文件(new File("Screen.png"))。


我没有使用paint方法,只是使用面板并向其添加组件。但是,在将面板保存为图像时,这些组件不可见。 - Babu R
请看我的编辑。在显示帧后,您必须调用saveImage函数。 - Alberto
请查看 ComponentImageCapture.java 以显示可见组件 - 向下滚动查看 另请参阅 和 Rob Camick 的一个类,可以减少从未显示的组件中获取图像的繁琐工作。在 为什么 JTable 标头不出现在图像中? 中还可以看到一些在显示之前呈现组件的其他技巧。 - Andrew Thompson
抱歉,我无法将面板及其中组件转换为图像。问题尚未解决。 - Babu R
但是你尝试过在 setVisible 之后调用 saveImage 吗?这样行吗? - Alberto

6

尝试这个示例程序,而不是使用getGraphics(),似乎你需要使用createGraphics()来创建你即将制作的BufferedImage

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SnapshotExample
{
    private JPanel contentPane;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Snapshot Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBackground(Color.WHITE);
        JLabel label = new JLabel("This JLabel will display"
                        + " itself on the SNAPSHOT", JLabel.CENTER);
        contentPane.add(label);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        makePanelImage(contentPane);
    }

    private void makePanelImage(Component panel)
    {
        Dimension size = panel.getSize();
        BufferedImage image = new BufferedImage(
                    size.width, size.height 
                              , BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        panel.paint(g2);
        try
        {
            ImageIO.write(image, "png", new File("snapshot.png"));
            System.out.println("Panel saved as Image.");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {           
                new SnapshotExample().displayGUI();
            }
        });
    }
}

请查看 ComponentImageCapture.java 以显示可见组件 - 向下滚动查看 另请参阅 和 Rob Camick 的一个类,可以减少从未显示的组件中获取图像的繁琐工作。在 为什么 JTable 标头不出现在图像中? 中还可以看到一些在显示之前呈现组件的其他技巧。 - Andrew Thompson
@AndrewThompson:非常感谢您提供这些宝贵的链接。我曾经在刚开始学习“Swing绘画”时看过这个问题,但那时整个概念都超出了我的理解范围。这一次,我希望能够从这些例子中学到更多知识:-) 再次感谢。干杯 - nIcE cOw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接