MarAja
MarAja

Reputation: 1597

Unable to set JPanel's Background in my Swing program.

I set a JPanel as a contentPane of my JFrame.

When I use:

jPanel.setBackground(Color.WHITE);

The white color is not applied.

But when I use:

jFrame.setBackground(Color.WHITE);

It works... I am surprised by this behaviour. It should be the opposite, shouldn't it?

SSCCE:

Here is an SSCCE:

Main Class:

public class Main {
    public static void main(String[] args) {
        Window win = new Window();
    }
}

Window Class:

import java.awt.Color;
import javax.swing.JFrame;

public class Window extends JFrame {
    private Container mainContainer = new Container();

    public Window(){
        super();
        this.setTitle("My Paint");
        this.setSize(720, 576);
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainContainer.setBackground(Color.WHITE); //Doesn't work whereas this.setBackground(Color.WHITE) works
        this.setContentPane(mainContainer);
        this.setVisible(true);
    }
}  

Container Class:

import java.awt.Graphics;
import javax.swing.JPanel;

public class Container extends JPanel {
    public Container() {
        super();
    }
    public void paintComponent(Graphics g) { 
    }
}

Upvotes: 5

Views: 583

Answers (2)

InsaneCoder
InsaneCoder

Reputation: 8288

The reason is very simple include the following line

super.paintComponent(g);

when you override paintComponent.

public void paintComponent(Graphics g) { 
        super.paintComponent(g);
    }

Now it works perfectly.

You should always do this unless you have a very specific reason to do so .

[PS:Change the colour to red or something darker to notice the difference as sometimes it becomes difficult to differentiate between JFrame's default grey colour and White colour]

Upvotes: 3

Loki
Loki

Reputation: 4128

With my testcode it works the way you expected it to work:

public class Main {

        public static void main(String[] args) {

            JFrame f = new JFrame();
            f.setSize(new Dimension(400,400));
            f.setLocationRelativeTo(null);

            JPanel p = new JPanel();
            p.setSize(new Dimension(20,20));
            p.setLocation(20, 20);

            //comment these lines out as you wish. none, both, one or the other
            p.setBackground(Color.WHITE);
            f.setBackground(Color.BLUE);

            f.setContentPane(p);

            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);

         }
      }

Upvotes: 1

Related Questions