How can I add an image to a panel

后端 未结 3 1722
我寻月下人不归
我寻月下人不归 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条回答
  •  旧时难觅i
    2021-01-29 16:11

    All you need to do is,

    1. Read image file.
    2. Draw image to background with help of Graphics object.

    just replace JPanel panel = new JPanel(); with below code.

             JPanel panel = new JPanel() {
                 @Override
                 protected void paintComponent(Graphics g) {
                     Image image = null;
                     try {
                         image = ImageIO.read(new URL("https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"));
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                     super.paintComponent(g);
                     g.drawImage(image, 0, 0, null);
                 }
             };
    

提交回复
热议问题