无法截取JFrame Java Swing的截图

时间:2014-02-24 18:30:51

标签: java image swing jframe screenshot

我尝试使用以下方法将JFrame保存为图像。

        try
        {
            BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            this.paint(image.getGraphics());
            ImageIO.write(image,"png", new File("Test.png"));
        }
        catch(Exception exception)
        {
            //code
            System.out.print("Exception unable to write image");
        }

我正在尝试保存屏幕截图,如下所示: enter image description here

我想在屏幕截图中找到标题

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DividedSquare {

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

public DividedSquare() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }

            JFrame frame = new JFrame("Testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new TestPane());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

public class TestPane extends JPanel {

    private TriangleShape baseTriangle;
    private Color[] colors;

    public TestPane() {
        colors = new Color[]{Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA};
    }

    @Override
    public void invalidate() {
        super.invalidate();

        baseTriangle = new TriangleShape(
                new Point(0, 0),
                new Point(getWidth(), 0),
                new Point(getWidth() / 2, getHeight() / 2));

    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();

        String text[] = new String[]{
            "123.123",
            "456.789",
            "012.315",
            "678.921"
        };

        FontMetrics fm = g2d.getFontMetrics();

        double angel = 0;
        for (int index = 0; index < 4; index++) {
            g2d.setColor(colors[index]);
            Path2D rotated = rotate(baseTriangle, angel);
            g2d.fill(rotated);
            Rectangle bounds = rotated.getBounds();
            int x = bounds.x + ((bounds.width - fm.stringWidth(text[0])) / 2);
            int y = bounds.y + (((bounds.height - fm.getHeight()) / 2) + fm.getAscent());
            g2d.setColor(Color.WHITE);
            g2d.drawString(text[index], x, y);
            angel += 90;
        }
        g2d.setColor(Color.BLACK);
        g2d.drawLine(0, 0, getWidth(), getHeight());
        g2d.drawLine(getWidth(), 0, 0, getHeight());
        g2d.dispose();


        try
        {
            BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            frame.paint(image.getGraphics());
            ImageIO.write(image,"png", new File("Practice.png"));
        }
        catch(Exception exception)
        {
            //code
            System.out.print("Exception to write image");
        }


    }

    public Path2D rotate(TriangleShape shape, double angel) {

        Rectangle bounds = shape.getBounds();
        int x = bounds.width / 2;
        int y = bounds.width / 2;

        return new Path2D.Float(shape, AffineTransform.getRotateInstance(
                Math.toRadians(angel),
                x,
                y));

    }

}

public class TriangleShape extends Path2D.Double {

    public TriangleShape(Point2D... points) {
        moveTo(points[0].getX(), points[0].getY());
        lineTo(points[1].getX(), points[1].getY());
        lineTo(points[2].getX(), points[2].getY());
        closePath();
    }

}
}

但我没有创建图像。我无法理解为什么。 我看了this,但我无法理解如何将其纳入我的案例中。

修改

基于评论,我尝试使用机器人类,但我无法知道从哪里调用此函数。如果我从paint()方法调用此函数,我将无法获取颜色和文本。

    void screenshot()
    {
        try
        {

            Robot robot = new Robot();
            // Capture the screen shot of the area of the screen defined by the rectangle
            Point p = frame.getLocationOnScreen();
            System.out.print("point" + p);
            BufferedImage bi=robot.createScreenCapture(new Rectangle((int)p.getX(),(int)p.getY(),frame.getWidth(),frame.getHeight()));
            ImageIO.write(bi, "png", new File("imageTest.png"));

        }
        catch(Exception exception)
        {
            //code
            System.out.print("Exception to write image");
        }

    }

1 个答案:

答案 0 :(得分:6)

至少有两种方法可以实现这一目标......

你可以......

使用Robot捕获屏幕截图。对于example

这个问题是需要花一点力气来定位你想要捕获的组件。它也只捕获一个矩形区域,所以如果组件是透明的,Robot将不会尊重这个...

你可以......

使用printAll将组件呈现给您自己的Graphics上下文,通常来自BufferedImage

printAll允许您打印组件,因为其目的不是将其打印到屏幕上,printAll禁用双缓冲,使您在不想渲染时更有效地使用屏幕上的组件,例如将其打印到打印机......

有关example