简体   繁体   English

如何将JPanel与其组件一起保存为JPEG

[英]How to save JPanel as JPEG with its components

I need to save a chessboard as a jpeg file. 我需要将棋盘保存为jpeg文件。 I know how to save a java component into JPEG. 我知道如何将java组件保存为JPEG。 But my problem is that I use JButtons as cells and when I try to save the whole chessboard, only the panel is saved. 但我的问题是我使用JButtons作为单元格,当我尝试保存整个棋盘时,只保存面板。 Does anybody know how to save a JComponent WITH ITS CHILD COMPNENTS into JPEG (png etc.) Thank you in advance. 有没有人知道如何将JComponent与其子系统COMPNENTS保存为JPEG(png等) 。提前感谢您。

You can print a Component (such as JPanel ) to any Graphics object. 您可以将Component (例如JPanel )打印到任何Graphics对象。 So, why not use the Graphics object of a BufferedImage and write it to disk. 那么,为什么不使用BufferedImageGraphics对象并将其写入磁盘。

void takePicture(JPanel panel) {
    BufferedImage img = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
    panel.print(img.getGraphics()); // or: panel.printAll(...);
    try {
        ImageIO.write(img, "jpg", new File("panel.jpg"));
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

This makes this JPanel 这使得这个JPanel

    JPanel panel = new JPanel();
    panel.add(new JButton("Hello"));
    panel.add(new JButton("World"));

Look like this: 看起来像这样:

在此输入图像描述

updated based on comments, many thanks to @MadProgrammer 根据评论更新,非常感谢@MadProgrammer

Check out Screen Image . 查看屏幕图像 It will allow you to create an image of any component in the frame. 它将允许您创建框架中任何组件的图像。 If you choose to make an image of a panel all the child components are included in the image. 如果您选择制作面板的图像,则所有子组件都包含在图像中。

Use Robot class to create a screen capture of your screen. 使用Robot类创建屏幕截屏。

Use this tutorial for help: Screen Capture using Robot class 使用本教程获取帮助: 使用Robot类进行屏幕捕获

Now for your chessboard, clip the image by calling subImage method of BufferedImage class. 现在为您的棋盘,通过调用BufferedImage类的subImage方法剪辑图像。

Here's the link on clipping BufferedImage 这是剪辑BufferedImage的链接

You can get Dimensions of you JPanel by calling getX(), getY(), getWidth() and getHeight() methods which you can pass into subImage method. 您可以通过调用getX(),getY(),getWidth()和getHeight()方法来获取JPanel的Dimensions,您可以将这些方法传递给subImage方法。 Manipulate the passing value by adding/substracting some value to get desired results. 通过添加/减去一些值来操纵传递值以获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM