为什么我的JPanel背景图片没有显示?

时间:2018-03-05 18:26:00

标签: java swing

我正在尝试将背景图像添加到Jpanel。以下是我使用

的代码
    private void createUIComponents() {
        JPanel panel1 = new BgPanel();
    } 


class BgPanel extends JPanel {
        Image bg = new ImageIcon("image.png").getImage();
        @Override
        public void paintComponent(Graphics g) {
            g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
        }
}

我正在使用IntelliJ,因此隐藏了大部分GUI代码。自定义创建的JPanel不应该是BgPanel,因此显示图像吗?我哪里出错?

我在尝试编译时得到以下内容:

Exception in thread "main" java.lang.NullPointerException
    at testGUI.$$$setupUI$$$(testGUI.java)
    at testGUI.<init>(testGUI.java:4)
    at testGUI.main(testGUI.java:11)

完整代码:

import javax.swing.*;
import java.awt.*;

public class testGUI {
    private JButton button1;
    private JPanel panel1;

    public static void main(String[] args) {
        JFrame frame = new JFrame("testGUI");
        frame.setContentPane(new testGUI().panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private void createUIComponents() {
        JPanel panel1 = new BgPanel();
    }

    class BgPanel extends JPanel {
        Image bg = new ImageIcon("imagelink.png").getImage();

        @Override
        public void paintComponent(Graphics g) {
            g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

 class BgPanel extends JPanel {
    private final BufferedImage image;
             public BgPanel() throws IOException {
      image = ImageIO.read(new File("path-to-image"));
         }
    @Override
            public void paintComponent(Graphics g) {
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        }

希望它会奏效 完整代码:

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class testGUI {
    private JButton button1;
    private JPanel panel1;

    public static void main(String[] args) throws IOException {
        JFrame frame = new JFrame("testGUI");
        frame.getContentPane().add(new BgPanel());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

 static class BgPanel extends JPanel {
private final BufferedImage image;
         public BgPanel() throws IOException {
             setPreferredSize(new Dimension(400,800));
  image = ImageIO.read(new File("C:\\Users\\Sourav\\Desktop\\fb\\IMG_20171209_181249.jpg"));
     }
@Override
        public void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
        }
    }
}