首页 > 解决方案 > 如何从外部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);
}
}

标签: java

解决方案


就在这里。一个类的实例可以具有它可以在自己的代码中访问的变量,并且您可以在实例化它时请求这些变量。所以在这里,当你声明你的绘图类时,你可以给它一个 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 方法的第二行声明了数组,然后在声明新图形时将其传递给图形。

希望这可以帮助!


推荐阅读