场景:我有一个 UI,其中包含一个 JPanel
(称为 topGrid
),顶部的 JFrame
中有一个网格布局等级。在 topGrid
中,我放置了另一个具有网格布局的 JPanel
(midGrid
)。在 midGrid
内部,是另一个 JPanel
(bottomGrid
),它有一个 JLabel
,我根据数组填充图像以及它们的实例在该数组中是什么。
目标:我希望 topGrid
将其 View 集中在 bottomGrid
中找到的特定对象上。 (想象一个游戏,当玩家图标移动时,游戏的网格移动到该图标的中心,并且当游戏启动时,它已经以用户为中心。)
我考虑过从 bottomGrid
获取 Point 并尝试将其传递给 topGrid
,但似乎没有提取正确的信息。我知道找到玩家所在位置的唯一方法是迭代所有组件并检查实例。必须为 topGrid 执行一次此操作,并为 midGrid 执行一次才能找到位于 BottomGrid 的玩家。然后传递点数据。然后在相应的 JPanel
上使用 setLocation() 减去距中心的距离。
还有其他人尝试过这个并有更有效或更优雅的方法吗?我还可以探索哪些其他选择?
感谢您的任何反馈。
在 topGrid
的 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);
}
}
}
在 midGrid
的 JPanel
中创建网格:
public void createOccupantIcons()
{
pnlGridOccupants.removeAll();
Occupant[] occs = sector.getOccupantsAsArray();
for ( Occupant occ : occs )
{
GalaxyOccupant occupant = new GalaxyOccupant(occ, sector);
pnlGridOccupants.add(occupant);
}
}
midGrid
中每个占用者的图像图标是从 bottomGrid
模型中的 IconRep
String
中提取的code> 类' JPanel
并根据 FlowLayout
中的需要添加到 JLabel
中。
视觉引用:
其中绿色方 block 是 topGrid
JPanel
,红色方 block 是 midGrid
JPanel
,黑色方 block 是bottomGrid
JPanel
,其中白色圆圈表示 JLabel
内的玩家图像。蓝色圆圈代表用户将看到游戏的视口(viewport),也是我希望玩家图标居中的位置。目前,用户可以使用视口(viewport)周围区域中非常不雅观的按钮来移动网格。这可能就足够了,但在游戏开始时,玩家必须移动网格,直到找到自己的图标。
最佳答案
您还可以查看JScrollNavigator
,检查here 。它允许您在整个世界的缩略图上导航,在相邻的滚动 Pane 中以全尺寸查看。
关于java - 如何让我的顶级 Jpanel 设置其相对于另一个 jpanel 网格中的 jlabel 的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12868865/