如果没有在 main 方法中调用,paint() 是如何运行的? [英] how is paint() running without being called in the main method?

查看:9
本文介绍了如果没有在 main 方法中调用,paint() 是如何运行的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个使用awt包的java图形初学者问题.我在网上找到了这段代码来绘制一些简单的图形.

This is a beginner question for java graphics using the awt package. I found this code on the web to draw some simple graphics.

import java.awt.*;
public class SimpleGraphics extends Canvas{

    /**
     * @param args
     */
    public static void main(String[] args) {
        SimpleGraphics c = new SimpleGraphics();
        c.setBackground(Color.white);
        c.setSize(250, 250);

        Frame f = new Frame();
        f.add(c); 
        f.setLayout(new FlowLayout()); 
        f.setSize(350,350);
        f.setVisible(true);
    }
    public void paint(Graphics g){
        g.setColor(Color.blue);
        g.drawLine(30, 30, 80, 80);
        g.drawRect(20, 150, 100, 100);
        g.fillRect(20, 150, 100, 100);
        g.fillOval(150, 20, 100, 100); 
    }
}

主方法中没有任何地方是在画布上调用paint().但是我运行了这个程序并且它可以工作,那么paint()方法是如何运行的?

Nowhere in the main method is paint() being called on the canvas. But I ran the program and it works, so how is the paint() method being run?

推荐答案

paint 方法由事件调度线程 (EDT) 调用,基本上不受您控制.

The paint method is called by the Event Dispatch Thread (EDT) and is basically out of your control.

它的工作原理如下:当您实现一个用户界面时(在您的情况下调用 setVisible(true)),Swing 启动 EDT.然后,这个 EDT 线程在后台运行,每当您的组件需要绘制时,它都会调用 paint 方法和适当的 Graphics 实例供您用于绘制.

It works as follows: When you realize a user interface (call setVisible(true) in your case), Swing starts the EDT. This EDT thread then runs in the background and, whenever your component needs to be painted, it calls the paint method with an appropriate Graphics instance for you to use for painting.

那么,什么时候需要"重新绘制组件?-- 例如当

So, when is a component "needed" to be repainted? -- For instance when

  • 调整窗口大小
  • 组件可见
  • 当你调用repaint
  • ...

简单地假设它在必要时被调用.

Simply assume that it will be called, whenever it is necessary.

这篇关于如果没有在 main 方法中调用,paint() 是如何运行的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆