Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

swing

jpanel

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) { 
    }
}
like image 670
MarAja Avatar asked Oct 03 '22 09:10

MarAja


1 Answers

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]

like image 183
Naveen Avatar answered Oct 07 '22 17:10

Naveen