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

标签 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();
    }
}

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

最佳答案

您可以尝试重写按钮的paintComponent()并引入一个标志needPaint。该标志默认为 true。

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

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

关于java - 如何在捕获 JPanel 时仅捕获选定的组件图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719983/

相关文章:

java - Android list 配置出现问题

java - ArrayList<Item> (其中 Item 是内部类)添加错误

java - getWidth() 对于面板返回 0

java - 在发送 HTTP 请求之前显示加载 jLabel

java - 我应该使用什么布局来获得我想要的 GUI?

java - Java中的JPanel填充

Java CC 问题 - "Expansion within "(...) *"can be matched by empty string"

java - Java 中的游戏碰撞检测

java - JLabel 是否可以根据变量值更改其文本?

java - 调整 JscrollPane 的大小