i cant get the program below, please explain

public class aaa {
public static void main(String[] args)
{

bbb b=new bbb();
    b.setVisible(true);
    b.setSize(400, 400);

}

}
class bbb extends JFrame
{
bbb()
{

draw d=new draw();
add(d);
}

}
class draw extends JComponent
{
public void paintComponent(Graphics g)
{
    Graphics2D g2=(Graphics2D) g;
    Ellipse2D rect=new Ellipse2D.Double();
    rect.setFrameFromCenter(50,50,70,70);
    g2.draw(rect);
    g2.setPaint(Color.blue);
    g2.fill(rect);
}
}

actually, i know this program will generate a frame and draw ellipse inside the rectangle... my only question is that, when will the method "paintcomponent(Graphics g)" be invoked... and i know that, it is a method inside "JComponent" but when will it be invoked...please give a brief explanation....

and one more question is that...it has parameter in type "Graphics"....but it has no object created for the class "Graphics", then how can we call its methods(methods in class "Graphics")..

i know this is stupid question, but i know something i have missed in concept...

Answers


paintComponent() is a method in the JComponent superclass.

Code in that class will create a Graphics object and call your method:

http://www.grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/javax/swing/JComponent.java#1054 http://www.grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/sun/awt/RepaintArea.java#227


  • paintComponent() will be invoked by the system when needed, you don't need to worry about calling it yourself.
  • You can use the param g that is passed to call Graphics methods, eg. g.setPaint() etc.

From the docs:

(...)the painting subsystem will determine that the component is damaged and will ensure that your paintComponent method is invoked.


Need Your Help

Memory leak on non retaining array

ios objective-c memory-leaks nsarray

In a non-ARC project I need to use non retaining arrays. I took the implementation from the old framework Three20. When I track my memory usage with Instruments, it shows me a leak for all my unret...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.