MountainThatCodes
MountainThatCodes

Reputation: 27

Why does setBackground cover other drawing?

i have the following code:

    private void ConvertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
    getContentPane().setBackground(new Color(50, 100, 200));
    Graphics g = getGraphics();
    g.drawString("tekst", 120, 120); 
    g.drawLine(175, 175, 140, 140); 
    g.setColor(Color.yellow); 
    g.fillOval(190, 120, 160, 160); 
    g.setColor(Color.red); 
    g.drawRoundRect(190, 110, 150, 120, 115, 115);  
}    

I want it to paint the form (after pressing the button) in the appropriate way, but what happens instead is it paints only the background after the first click and after the second click it paints the rest of the objects. When i try this approach instead, with overriding paint method:

public void paint(Graphics g){
    setBackground(new Color(50, 100, 200));       
    g.drawString("tekst", 120, 120); 
    g.drawLine(175, 175, 140, 140); 
    g.setColor(Color.yellow); 
    g.fillOval(190, 120, 160, 160); 
    g.setColor(Color.red); 
    g.drawRoundRect(190, 110, 150, 120, 115, 115);  
}

and having

private void ConvertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
    repaint();  
}

then the background is of grey color instead of blue and the button disappears (appears only after i have the mouse right over it).

So, finally my question is: What exactly is wrong with both of these examples (i want to understand both, since this is only a learning exercise i'd like to know what is happening rather than simply finding a solution), and which approach is better? Thanks in advance, i hope I didn't miss a similar question on this site, if i did i'm sorry!

Upvotes: 1

Views: 281

Answers (2)

camickr
camickr

Reputation: 324147

Graphics g = getGraphics();

Don't use getGraphics() to do custom painting. That type of painting is only temporary and will be lost the next time Swing repaints the component. Also, don't override the paint() method. To set the background Color of a component you just do:

component.setBackground(...);

Custom painting is done by overriding the paintComponent() method of your custom component. Don't forget to invoke super.paintComponent() at the start. Read the Swing tutorial on Custom Painting for more information.

Upvotes: 2

Guillaume
Guillaume

Reputation: 14671

The method where you override paint is correct, you should use:

g.setColor(new Color(50, 100, 200));
g.fillRect(0, 0, c.getWidth(),c.getHeight());

instead of:

setBackground(new Color(50, 100, 200));   

Or alternatively set the background color and in your paint() method, call the super implementation before painting anything else:

super.paint(g);

Upvotes: 2

Related Questions