如何在捕获JPanel时仅抓取选定的组件图像?

时间:2014-09-08 08:20:53

标签: java swing jpanel

带有3个JButton的JPanel,我只需要捕获其中的两个......

public static void grabScreenShot(JPanel panel) {
    BufferedImage image = (BufferedImage) panel.createImage(
            panel.getSize().width, panel.getSize().height);
    panel.paint(image.getGraphics());
    File file = null;
    file = new File("Customers");
    if (!file.exists()) {
        file.mkdir();
    }

    try {
        file = new File("Customers" + File.separator
                + String.valueOf(System.currentTimeMillis()));
        ImageIO.write(image, "png", file);
        System.out.println("Image was created");
    } catch (IOException e) {
        System.out.println("Had trouble writing the image.");
        e.printStackTrace();
    }
}

如何避免捕获不必要的组件。?

1 个答案:

答案 0 :(得分:1)

您可以尝试覆盖按钮的paintComponent()并引入标记needPaint。默认情况下该标志为真。

if (needPaint) {
    super.paintComponent(g);
}

在你的grabScreenShot()中,将标志设置为false以隐藏按钮,并在panel.paint(image.getGraphics());调用后将其重置为