how to save panel as image in swing?

前端 未结 2 1299
青春惊慌失措
青春惊慌失措 2020-12-06 17:22

Hi i want to convert panel which contains components like label and buttons to image file.

I have done the following code. The image was saved. but the content of th

2条回答
  •  无人及你
    2020-12-06 17:52

    Here try this example program, instead of using getGraphics() seems like you have to use createGraphics() for the BufferedImage you are about to make.

    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    public class SnapshotExample
    {
        private JPanel contentPane;
    
        private void displayGUI()
        {
            JFrame frame = new JFrame("Snapshot Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            contentPane = new JPanel();
            contentPane.setOpaque(true);
            contentPane.setBackground(Color.WHITE);
            JLabel label = new JLabel("This JLabel will display"
                            + " itself on the SNAPSHOT", JLabel.CENTER);
            contentPane.add(label);
    
            frame.setContentPane(contentPane);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
    
            makePanelImage(contentPane);
        }
    
        private void makePanelImage(Component panel)
        {
            Dimension size = panel.getSize();
            BufferedImage image = new BufferedImage(
                        size.width, size.height 
                                  , BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            panel.paint(g2);
            try
            {
                ImageIO.write(image, "png", new File("snapshot.png"));
                System.out.println("Panel saved as Image.");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    
        public static void main(String... args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {           
                    new SnapshotExample().displayGUI();
                }
            });
        }
    }
    

提交回复
热议问题