簡體   English   中英

如何從外部paint() 繪制變量?

[英]How do you paint a variable from outside paint()?

我希望能夠從外部paint() 訪問數組。 有沒有辦法在 main 方法中聲明數組,然后在 paint() 中使用值並用 g.drawString() 繪制出來?

public class design
{
public static void main (String[] args)
{
    JFrame window = new JFrame ("Game Screen");
    window.getContentPane ().add (new drawing ());
    window.setSize (500, 500);
    window.setVisible (true);
    window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}

class drawing extends JComponent
{
public void paint (Graphics g)
{
    int[] [] word = {{5, 3, 0, 0, 7, 0, 0, 0, 0},
            {6, 0, 0, 1, 9, 5, 0, 0, 0},
            {0, 9, 8, 0, 0, 0, 0, 6, 0},
            {8, 0, 0, 0, 6, 0, 0, 0, 3},
            {4, 0, 0, 8, 0, 3, 0, 0, 1},
            {7, 0, 0, 0, 2, 0, 0, 0, 6},
            {0, 6, 0, 0, 0, 0, 2, 8, 0},
            {0, 0, 0, 4, 1, 9, 0, 0, 5},
            {0, 0, 0, 0, 9, 0, 0, 7, 9}};
    Graphics2D g2 = (Graphics2D) g;
    Rectangle rect;
    for (int x = 0 ; x < 9 ; x++)
    {
        for (int y = 0 ; y < 9 ; y++)
        {
            rect = new Rectangle (x * 50 + 5, y * 50 + 5, 50, 50);
            g2.draw (rect);
            if (word [y] [x] == 0)
            {
                g.drawString (" ", x * 50 + 30, y * 50 + 30);
            }
            else
                g.drawString (Integer.toString (word [y] [x]), x * 50 + 25, y * 50 + 35);
        }
    }
    g.fillRect (153, 5, 3, 450);
    g.fillRect (303, 5, 3, 450);
    g.fillRect (5, 153, 450, 3);
    g.fillRect (5, 303, 450, 3);
}
}

就在這里。 class 的實例可以具有可以在自己的代碼中訪問的變量,並且您可以在實例化時請求這些變量。 所以在這里,當你聲明你的繪圖 class 時,你可以給它一個 int[][] 的變量。 這看起來像

class drawing extends JComponent {
    private int[][] word;
    public drawing(int[] [] word) { 
        //This replaces your normal contstructor. So instead of calling "new drawing()" you will call 
        //"new drawing(word)" where word is your instantiated array.
        this.word = word; //this assigns the word you were given to your class's variable
    }
    public void paint(Graphics g) { ...

在這里你繼續,但你不必聲明你的數組。 您可能已經在 main 方法的第二行聲明了數組,然后在聲明新圖形時將其傳遞給圖形。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM