paint()如何在主要方法中不被调用的情况下运行? [英] how is paint() running without being called in the main method?

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

问题描述

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

  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()方法是如何运行的?

c> paint
方法由事件调度线程(EDT)调用,基本上不受你控制。



它的工作原理如下:你实现一个用户界面(在你的情况下调用 setVisible(true)),Swing启动EDT。这个EDT线程然后在后台运行,并且无论何时需要绘制组件,它都会使用适当的 Graphics 调用 paint 方法$ b> b

那么,什么时候需要重绘一个组件? - 例如当


  • 窗口被调整大小

  • 组件变得可见
  • >
  • 当您调用 repaint

  • ...

>

只要有必要就调用它。


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); 
    }
}

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?

解决方案

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

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

  • The window is resized
  • The component is made visible
  • When you call repaint
  • ...

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

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

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