I am designing a program that contains two JPanels within a JFrame, one is for holding an image, the other for holding GUI components(Searchfields etc). I am wondering how d
I'd like to suggest a more simple way,
image = ImageIO.read(new File(path));
JLabel picLabel = new JLabel(new ImageIcon(image));
Yayy! Now your image is a swing component ! add it to a frame or panel or anything like you usually do! Probably need a repainting too , like
jpanel.add(picLabel);
jpanel.repaint();
You can use the JLabel.setIcon() to place an image on the JPanel as shown here.
On the other hand, if you want to have a panel with a background, you can take a look at this tutorial.
There is no need to manually invoke paintComponent() from a constructor. The problem is that you passing null for a Graphics object. Instead, override paintComponent() and you use the Graphics object passed in to the method you will be using for painting. Check this tutorial. Here is an example of JPanel with image:
class MyImagePanel extends JPanel{
BufferedImage image;
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null){
g.drawImage(image, 0, 0, this);
}
}
}