繁体   English   中英

为什么在Java swing中没有将新的Graphics对象传递给paintComponent方法?

[英]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)捕获或打印组件,也应该使用printprintAll

看看AWT和Swing中的绘画

它们是类似的问题。 Swing库根据JVM的请求由Graphics对象创建Graphics对象,并在JVM调用此方法时将其传递到paintComponent(Graphics g)方法中。 因为您自己没有直接调用此方法,所以您永远看不到正在创建的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM