views:

145

answers:

2

I am having the below code.

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 i.e gray.

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

Thank you.

+3  A: 

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.

Chris Dennett
+1  A: 

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".

camickr
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Canvas.html#paint%28java.awt.Graphics%29"Most applications that subclass Canvas should override this method in order to perform some useful operation (typically, custom painting of the canvas). The default operation is simply to clear the canvas. Applications that override this method need not call super.paint(g)."I assume that their VizCanvas subclasses Canvas, but their constructor seems a bit bare. Hmm.
Chris Dennett