java - 如何从外部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);
}
}
解决方案
就在这里。一个类的实例可以具有它可以在自己的代码中访问的变量,并且您可以在实例化它时请求这些变量。所以在这里,当你声明你的绘图类时,你可以给它一个 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 方法的第二行声明了数组,然后在声明新图形时将其传递给图形。
希望这可以帮助!
推荐阅读
- mongodb - 根据类型处理 MongoDB 错误
- javascript - 如何截断 JavaScript 方法中列出的变量?
- google-chrome - Windows 上铬崩溃的事后调试?
- python - 从具有以相同值开头的键的字典中提取最大值
- c - 简单的switch和case,与卡片相关,C语言
- laravel - Laravel关注按钮未捕获请求失败代码500
- java - 来自 Spring 数据的 Page 的映射如何工作?
- r - 制作总和列的 R DataTable 解决方案
- python - NameError:名称“高度”未在第 10 行定义
- python - 如何修改 if/else 块以按预期捕获异常?