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) { 
    }
}
                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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With