简体   繁体   中英

Java2d: JPanel set background color not working

I have the code shown below:

public VizCanvas(){
    {
        this.setBackground(Color.black);
        this.setSize(400,400);
    }
}

It worked fine and displays the panel in black background. But when I implement the paint method, which does nothing, the color changes to default color ie gray.

I tried to set graphics.setColor() but it didn't help.

You need to do a fill of the canvas to your background colour in the painting method. Something along the lines of:

g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());

After that, draw whatever you need to. You could also try calling super.paint(g) in the paint method instead before doing anything.

Custom painting should be done by overriding the paintComponent() method, NOT the paint() method. Then all you do is invoke super.paintComponent() to get the background painted.

Setting the size of the component does nothing. The layout manager will override the size. You should be setting the preferred size or override the getPreferredSize() method.

Read the Swing tutorial for Swing basics. There are sections on "custom painting" and "using layout managers".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM