How to add an image to a JPanel?

前端 未结 14 1544
陌清茗
陌清茗 2020-11-22 00:01

I have a JPanel to which I\'d like to add JPEG and PNG images that I generate on the fly.

All the examples I\'ve seen so far in the Swing Tutorials, specially in the

14条回答
  •  遇见更好的自我
    2020-11-22 00:33

    Here's how I do it (with a little more info on how to load an image):

    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    
    public class ImagePanel extends JPanel{
    
        private BufferedImage image;
    
        public ImagePanel() {
           try {                
              image = ImageIO.read(new File("image name and path"));
           } catch (IOException ex) {
                // handle exception...
           }
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters            
        }
    
    }
    

提交回复
热议问题