1. 程式人生 > >paint之Graphics

paint之Graphics

ble src n) 編程習慣 調用 mage 被調用 getc rect

技術分享

在paint方法裏面,這個Graphics類就相當於一支畫筆。而且就畫在那個component裏面,比如frame。

看例子代碼:

import java.awt.*;

public class TestPaint {
    public static void main(String[] args) {
        new PaintFrame();
    }
}

class PaintFrame extends Frame {
    public PaintFrame() {
        setBounds(200,200,640,480);
        setVisible(
true); } public void paint(Graphics g) {//重寫 Color c = g.getColor();//這支畫筆有一個畫筆它自己的顏色,然後拿到當前這支畫筆的顏色。 g.setColor(Color.red); g.fillOval(50,50,30,30);//畫一個實心的橢圓,畫橢圓是采用內切矩形來畫的。50,50是左上角的坐標,30,30是矩形的寬與高。 g.setColor(Color.green); g.fillRect(80,80,40,40);//畫一個矩形 g.setColor(c);//
弄回原來那支筆的顏色,這是一個良好的編程習慣。 } }

技術分享

但是大家看,我們並沒有調用這個paint方法。那麽看見這個paint方法非常特殊,它是自動調用的!

其實這個窗口建造出來之後就有一支畫筆graphics,然後你再調用paint方法(自動)之後會把這個畫筆傳遞給你。你只要拿到這只畫筆然後重寫這個方法,想畫什麽就畫什麽就行了。

那麽這個paint方法什麽時候會被調用呢? 當這個frame需要被重畫的時候會被自動調用。比方說,我們的窗口第一次顯示的時候會被調用,改變窗口大小的時候會被調用……因為你重新顯示嘛那你肯定要把新的東西畫出來別人才能看到啊。

paint之Graphics