I am trying to add a background image to a Jpanel. Below is the code I'm using
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);
}
}
I am using IntelliJ so most of the GUI code is hidden. Shouldn't the custom created JPanel be a BgPanel and therefore display the image? Where have I gone wrong?
I am getting the following when trying to compile:
Exception in thread "main" java.lang.NullPointerException
at testGUI.$$$setupUI$$$(testGUI.java)
at testGUI.<init>(testGUI.java:4)
at testGUI.main(testGUI.java:11)
Full Code:
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);
}
}
}