Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将java GUI组件绘制到图像文件_Java_Paint_Image File - Fatal编程技术网

将java GUI组件绘制到图像文件

将java GUI组件绘制到图像文件,java,paint,image-file,Java,Paint,Image File,假设我有 JButton test = new JButton("Test Button"); 我想把这个按钮画到一个图像对象中,然后保存到一个文件中 我试过这个: BufferedImage b = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB); test.paint(b.createGraphics()); File output = new File("C:\\screenie.png"); try { Im

假设我有

JButton test = new JButton("Test Button");
我想把这个按钮画到一个图像对象中,然后保存到一个文件中

我试过这个:

BufferedImage b = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
test.paint(b.createGraphics());

File output = new File("C:\\screenie.png");

try
{
    ImageIO.write(b, "png", output);
}
catch (IOException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

这段代码生成了一个空的500x500 PNG文件。有人知道如何将GUI组件绘制到图像文件中吗?

图像不是空的,它在0,0处包含一个大小为0x0的按钮

解决方案:必须手动添加布局或设置按钮的大小


注意:要测试它,首先在JFrame上渲染组件。这使您能够快速看到将发生什么。

请提供一个实际编译的小型自包含示例。在您的代码片段中,使用了“offScreen”,但没有声明。