JAVA method的問題(棋盤格) 含程式碼

import javax.swing.*;

import java.awt.*;

public class GraphPaper extends JFrame {

Color color;

// class constants

private static final int FRAME_SIZE = 600;

private static final int NUM_SQUARES = 10;

private static final int SQUARE_SIZE = FRAME_SIZE/NUM_SQUARES;

// private instance variables

private Point [] [] graphPoints;

public static void main (String [] args) {

GraphPaper gp = new GraphPaper();

}

public GraphPaper() {

super("Graph Paper");

setSize(FRAME_SIZE, FRAME_SIZE);

setVisible(true);

//setBackground(Color Green);

graphPoints =

new Point [NUM_SQUARES+1][NUM_SQUARES+1];//[11] [11]

for (int r = 0; r < graphPoints.length; r++)

for (int c = 0; c < graphPoints[r].length; c++)

graphPoints[r][c] =

new Point (c*SQUARE_SIZE, r*SQUARE_SIZE);

}

public void paint (Graphics g) {

for(int r = 0; r <= NUM_SQUARES - 1; r++)

for(int c = 0; c <= NUM_SQUARES - 1; c++)

g.drawLine(graphPoints[r][c].x, graphPoints[r][c].y, graphPoints[r+1][c].x, graphPoints[r+1][c].y);

for(int r = 0; r <= NUM_SQUARES - 1; r++)

for(int c = 0; c <= NUM_SQUARES - 1; c++)

g.drawLine(graphPoints[r][c].x, graphPoints[r][c].y, graphPoints[r][c+1].x, graphPoints[r][c+1].y);

//JOptionPane.showMessageDialog(null, "Click OK to exit");

//System.exit(0);

}

我要問的問題

在mian或constructor裡面都沒有呼叫 public void paint (Graphics g)這個method的,請問這個程式是從哪裡執行那個method的

請大大們幫幫我解說一下吧~~謝謝

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    在Swing下, paint()是預設裡就被呼叫了....

    當你的元件 paint() 被呼叫時, 在 Swing 的設計下,

    預設的呼叫順序情況如下.

    Step 1: paintComponent(Graphics g): 畫出目前元件的樣子

    Step 2: paintBorder(Graphics g): 畫出目前的外框

    Step 3: paintChildren(Graphics g): 呼叫所包含元件的 paint()

    所以如果你的元件, 直接 override paint method,

    然後不寫任何程式碼.

    public void paint(Graphics g){

    }

    那麼你的元件 外框 所有的子元件都不會被畫出來.

    JDK 中 paintComponent method 實作長相大致上如下:

    protected void paintComponent(Graphics g) {

    if (ui != null) {

    // 如果有安裝 UI Delegate, 則呼叫 ui 的 update method

    Graphics scratchGraphics = (g == null) ? null : g.create();

    try {

    ui.update(scratchGraphics, this);

    }

    finally {

    scratchGraphics.dispose();

    }

    }

    }

    其中 ui 的 update method 實作, 如下:

    public void update(Graphics g, JComponent c) {

    if (c.isOpaque()) {

    // 不透明

    // 下面這段就是為什麼, 元件重畫時會閃爍的原因

    g.setColor(c.getBackground());

    g.fillRect(0, 0, c.getWidth(),c.getHeight());

    }

    paint(g, c); // <----- 這邊才是畫出預設元件的畫面

    }

    想要有進一步的了解paint和Swing和awt的關係可以去下方連結看看:

    http://java.sun.com/products/jfc/tsc/articles/pain...

    希望這樣有幫到你

    豚仔

  • 7 years ago

    我老婆都在這家買的: http://slssg.tk/ 很贊的!!

Still have questions? Get your answers by asking now.