为许多对象初始化引用变量? [英] Initialize reference variables for many objects?

查看:24
本文介绍了为许多对象初始化引用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为我的 Java 课程构建战舰游戏的网格时遇到了一些麻烦.到目前为止,我可以轻松地创建一个 for 循环来将 JPanel 或 JButton 对象添加到 JFrame.但是,我的问题是在玩游戏时我需要再次使用这些面板或按钮(例如单击按钮以查看您的对手是否在该方格上放置了一艘船,等等).Java 中是否有一种简单的方法来初始化大量对象的引用变量?还是我必须单独申报所有这些?

I'm having a little trouble building the grids for a Battleship game for my Java class. So far, I can easily make a for loop to add JPanel or JButton objects to the JFrame. However, my issue is that I'll need to use those Panels or Buttons again when playing the game (such as clicking on a button to see if your opponent put a ship on that square, et cetera). Is there a simple way in Java to initialize reference variables for a LOT of objects? Or will I have to declare all of them individually?

推荐答案

您可以尝试使用 JPanel(或任何其他对象)的多维数组.创建一个与网格大小相同的数组.下面这行初始化了一个 5 行 5 列的数组.

You could try a multi dimensional array of JPanels (or any other object). Create an array with the same size as your grid. The line below initializes an array with 5 rows and 5 columns.

JPanel[][] battleField = new JPanel[5][5];

使用嵌套的 for 循环在数组中创建面板.

Use nested for loops to create the panels in the array.

for (int rowIndex = 0; rowIndex < battleField.length; rowIndex++)
{
    for (int cellIndex = 0; cellIndex < battleField[rowIndex]; cellIndex++)
    {
         battleField[rowIndex][cellIndex] = new JPanel();
    }
}

如果您想稍后引用 BattleField 数组,您只需将其设为实例变量即可.

If you want to reference the battleField array later on you would just make it into a instance variable.

这篇关于为许多对象初始化引用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆