【发布时间】: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