![](/img/trans.png)
[英]how to access Graphics object outside paintComponent() method
[英]why is a new Graphics object not passed to paintComponent method in Java swing?
我正在阅读swing tutorial
。 从那里提到的:
The paintComponent method of JComponent is automatically called
when a frame is drawn/re-drawn.
但是,我不明白的是传递给它的Graphics Object
是什么。 我没有看到instanstiated
并传递任何Graphics
类型的新对象。 那么这一切如何发生?
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.drawimage(image,x,y,null);
//
}
我猜想动作actionlisteners
也有类似情况。 但是,在这种情况下, actionPerformed
自动时调用event
发生时,如button click
和事件被传递到actionPerformed
。 无需单独调用此方法并传递Actionevent object
。 但是我不知道用paintComponent
方法是如何发生的。
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
//do something
}
});
谢谢
Graphics
对象是由paint子系统创建的。
您永远不要自己调用paintComponent
而应该只允许paint系统处理它。 即使您想使用Graphics
上下文(例如BufferedImage)捕获或打印组件,也应该使用print
或printAll
它们是类似的问题。 Swing库根据JVM的请求由Graphics对象创建Graphics对象,并在JVM调用此方法时将其传递到paintComponent(Graphics g)
方法中。 因为您自己没有直接调用此方法,所以您永远看不到正在创建的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.