Reputation: 31252
I am reading swing tutorial
. From what is mentioned there:
The paintComponent method of JComponent is automatically called
when a frame is drawn/re-drawn.
But, what I do not understand is what is the Graphics Object
that is passed to it. I do not see
any new object of Graphics
type being instanstiated
and passed. so how does all this happen?
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.drawimage(image,x,y,null);
//
}
I guess it is a similar situation with actionlisteners
. But in this case, The actionPerformed
is called automatically when event
occurs such as button click
and the events gets passed to the actionPerformed
. There is no need to separately call this method and pass the Actionevent object
. But I do not understand how it happens with paintComponent
method.
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
//do something
}
});
Thanks
Upvotes: 0
Views: 452
Reputation: 347194
The Graphics
object is created by the paint sub system.
You should never be calling paintComponent
yourself and should simply allow the paint system deal with it. Even if you wanted to capture or print the component using your Graphics
context (from something like BufferedImage), you should be using print
or printAll
Take a look at Painting in AWT and Swing
Upvotes: 4
Reputation: 285403
They are similar issues. The Graphics object is created by the Swing library at the request o the JVM and passed into the paintComponent(Graphics g)
method when the JVM makes this method call. Because you yourself are not directly calling this method, you never see the object being created.
Upvotes: 3