Java – Drawing an Image to a JPanel within a JFrame


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 do I draw the Image to the first JPanel within the JFrame?

Here is a sample code from my constructor :

public UITester() {
    Container container = getContentPane();
    container.setLayout(new FlowLayout());
    searchText = new JLabel("Enter Search Text Here");
    imagepanel = new JPanel(new FlowLayout());
   //other constructor code


public void paintComponent(Graphics g){
    g.drawImage(img[0], -50, 100, null);

I was trying to override the paintComponent method of JPanel to paint the image, but this causes a problem in my constructor when I try to write :


As it will only allow me to pass the method null, and not Graphics g, anybody know of a fix to this method or another method i can use to draw the image in the JPanel? Help is appreciated! 🙂

All the best and thanks in advance!

Best Solution

I'd like to suggest a more simple way,

  image = 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