gpt4 book ai didi

java - 如何在swing中将面板保存为图像?

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:53 26 4
gpt4 key购买 nike

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

我已经完成了以下代码。图像已保存。但面板的内容不可见或未保存。谁能告诉我如何保存面板及其组件。

代码:

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

最佳答案

这段代码对我有用(在 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

我将 saveImage 作为 main 中的最后一次调用,并使用了用户目录中的一个文件 (new File("Screen.png")) 作为 nIcE cOw说。

关于java - 如何在swing中将面板保存为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11272938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com