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
-
1See also Painting in AWT and Swing.trashgod– trashgod2014年01月14日 02:04:42 +00:00Commented Jan 14, 2014 at 2:04
2 Answers 2
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
8 Comments
paintComponent method is called, a new Graphics object is created. That would be waste of resources correct?Graphics object is changed/created when the window is attached to a native peer. Then, basically, all the components share the same Graphics context until the window is closed. This is why you should NEVER call dispose on a Graphcis context you did not createrepaint() needs to be explicitly called, whereas paint() not. If I have, paintComponent how does this work?repaint puts a paint event onto the Event Queue, which is passed to the RepaintManager which makes decisions about what and when something should be painted. paint is the action, repaint is the request.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.
Comments
Explore related questions
See similar questions with these tags.