The scenario: I have a UI that contains a JPanel
(call it topGrid
) with a grid layout in a JFrame
at the top level. Within topGrid
, I have placed another JPanel
(midGrid
) with grid layout. Inside midGrid
, is another JPanel
(bottomGrid
) that has a JLabel
that I populate with images depending on an array and what their instance is within that array.
The goal: I would like the topGrid
to center its view on a specific object found in bottomGrid
. (Picture a game that as the player icon moves, the game's grid moves to center on that icon and also when the game is started it is already centered for the user.)
I've considered getting the Point from bottomGrid
and trying to pass it over to topGrid
but doesn't seem to pull the correct information. The only way i know to find where the player is, is to iterate through all the components and check instances. this would have to be done once for the topGrid and again for midGrid to find the player at bottomGrid. then pass the Point data. Then use setLocation() on the appropriate JPanel
minus the distance from the center.
Has anyone else tried this and have a more effective or elegant way to go about it? What other options could I explore?
Thanks for any feedback.
Creating the grid within topGrid
's JPanel
:
public void createTopGrid()
{
int rows = galaxy.getNumRows();
int columns = galaxy.getNumColumns();
pnlGrid.removeAll();
pnlGrid.setLayout(new GridLayout(rows, columns));
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
Position pos = new Position(galaxy, row, col);
Sector sector = galaxy.getSector(pos);
GalaxySector sectorUI = new GalaxySector(sector);
pnlGrid.add(sectorUI);
}
}
}
Creating the grid within midGrid
's JPanel
:
public void createOccupantIcons()
{
pnlGridOccupants.removeAll();
Occupant[] occs = sector.getOccupantsAsArray();
for ( Occupant occ : occs )
{
GalaxyOccupant occupant = new GalaxyOccupant(occ, sector);
pnlGridOccupants.add(occupant);
}
}
The Image icons for each occupant in the midGrid
are pulled from an IconRep
String
in the model in the bottomGrid
class' JPanel
and added into a JLabel
as needed in FlowLayout
.
For visual reference:
Where green square is topGrid
JPanel
, red squares are midGrid
JPanel
, and the black square is the bottomGrid
JPanel
with the white circle for the player image inside a JLabel
. The blue circle represents a viewport the user will see the game through and is where I want the player icon to be centered to. Currently the user can move the grid's using very inelegant buttons in the area around the viewport. That might be sufficient but at the start of the game the player has to move the grid around until they can locate their icon.