如何将窗口内容保存为图像

时间:2011-01-18 14:39:18

标签: java swing

我想将JPanel的内容捕获为图像,以便我可以完全按照用户的看法存储它。有没有一种相对简单的方法来摆动?

3 个答案:

答案 0 :(得分:7)

从这里http://forums.oracle.com/forums/thread.jspa?threadID=2156176&tstart=0

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SavePaint extends JPanel
{

    public SavePaint()
    {
        JFrame frame = new JFrame("TheFrame");
        frame.add(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,400);
        frame.setVisible(true);

        try
        {
            BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = image.createGraphics();
            frame.paint(graphics2D);
            ImageIO.write(image,"jpeg", new File("/home/deniz/Desktop/jmemPractice.jpeg"));
        }
        catch(Exception exception)
        {
            //code
        }
    }

    protected void paintComponent(Graphics g)
    {
        g.drawRect(50,50,50,50);
    }

    public static void main(String[] args)
    {
        new SavePaint();
    }
}

答案 1 :(得分:3)

答案 2 :(得分:0)

使用new java.awt.Robot().createScreenCapture(screenRect)