tags:

views:

56

answers:

3
import javax.swing.*;
import java.awt.*;

public class Fr extends JFrame{

    Fr(String s){
        super(s);
        setSize(200,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint(Graphics gr){
        gr=getGraphics();
        gr.fillRect(50, 50, 20, 20);
    }

    public static void main(String[] args){
        Fr f=new Fr("Window");
        f.getGraphics().setColor(JColorChooser.showDialog(null,"Color",null));
        f.getGraphics().fillRect(100,100,20,20);
    }
}

It creates a window, method "paint" draw first rect after creates window color selection, I choose the color (red) and drawn the second rect...black Why?

+2  A: 

The component's paint method is called when swing determines it needs to be repainted.

So probably what is happening, is paint() is called as soon as the Frame is created and displayed. The graphics color happens to be black at this point.

Then, you set a color and call "drawRect" on the graphics object. Nothing happens because you aren't in the paint method. At some point down the road, swing determines it needs to repaint the frame and calls it's method with a newly initialized Graphics object. It's color is set to the default black. You get another black rectangle.

The solution is to add a field to your Fr object. "rectangleColor" for example. Your JColorChooser should update this field. When Fr's paint is called, it should refer to this property to set the graphics color.

If you want to force a component to repaint itself, you should call the repaint() method on it.

Finally, there's no sense in setting gr = getGraphics(). You already have an initialized Graphics object passed to you in the paint method.

z5h
thank, seems I understand
rebel_UA
+1  A: 

You should never override the paint() method of a JFrame.

Read the secton from the Swing tutorial on Custom Painting for examples on custom painting.

camickr
ok, I was don't khow, I will read this linkthank
rebel_UA
A: 
import javax.swing.*;
import java.awt.*;


public class Fr extends JFrame{
    private static Color c=new Color(0,0,0,0);
    Fr(String s){
        super(s);
        setSize(200,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
        public void paint(Graphics gr){
            gr.fillRect(50, 50, 20, 20);
            gr.setColor(c);
            gr.fillRect(100,100,20,20);
        }
    public static void main(String[] args){
    Fr f=new Fr("Window");
    c=JColorChooser.showDialog(null,"Color",null);
    f.repaint();
    }
}

thank for guy of Toronto =)

rebel_UA