Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize reference variables for many objects?

Tags:

java

swing

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?

like image 326
Z. Charles Dziura Avatar asked Dec 13 '22 18:12

Z. Charles Dziura


1 Answers

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];

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();
    }
}

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

like image 55
willcodejavaforfood Avatar answered Jan 04 '23 22:01

willcodejavaforfood