【问题标题】:How do you paint a variable from outside paint()?如何从外部paint() 绘制变量?
【发布时间】:2020-05-22 01:52:00
【问题描述】:

我希望能够从外部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);
}
}

【问题讨论】:

  • 你必须从paint绘画,但可以访问实例字段`你画错了,请检查this example

标签: java


【解决方案1】:

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

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2013-11-29
    • 2011-04-12
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多