How can I add an image to a panel

后端 未结 3 1719
我寻月下人不归
我寻月下人不归 2021-01-29 16:04

edit// my question is simpler than the other one so please just answer here. the other question looks too complicated for me to understand.

I want to add an image to a p

3条回答
  •  攒了一身酷
    2021-01-29 16:19

    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            
        }
    
    }
    

提交回复
热议问题