量産メモ帳

忘れっぽいのでメモを残しています。浅く適当に書きます。

画面のスクリーンショットをファイルに保存

スポンサーリンク

画面のスクリーンショットをファイルに保存する方法を調べていたら、以下の URL に辿り着きました。



例えば JDialog の場合、こんな感じでできます*1

/* ダイアログを閉じる時にスクリーンショットをファイルに保存。 */


final JDialog dialog = new JDialog();
// ・・・中略・・・
dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
        try {
            Robot robot = new Robot();
            Rectangle rectangle = new Rectangle(dialog.getX(), dialog.getY(), dialog.getWidth(), dialog.getHeight());
            BufferedImage image = robot.createScreenCapture(rectangle);
            File file = new File("dialog.png");
            ImageIO.write(image, "png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
dialog.setVisible(true);


意外と簡単にできて助かりました。

*1:ただしこのコード自体はコンパイルしてないので、スペルミスとかあるかも。