【发布时间】:2012-10-13 00:32:54
【问题描述】:
场景:我有一个 UI,其中包含 JPanel(称为 topGrid),在顶层 JFrame 中有一个网格布局。在topGrid 中,我放置了另一个带有网格布局的JPanel (midGrid)。在midGrid 内部,是另一个JPanel (bottomGrid),它有一个JLabel,我根据数组及其实例在该数组中填充图像。
目标:我希望topGrid 将其视图集中在bottomGrid 中找到的特定对象上。 (想象一个游戏,随着玩家图标的移动,游戏的网格移动到该图标的中心,并且当游戏开始时,它已经以用户为中心。)
我考虑过从bottomGrid 获取点并尝试将其传递给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 中提取的,JPanel 并根据需要添加到 JLabel 中的 FlowLayout .
视觉参考:
绿色方块是topGridJPanel,红色方块是midGridJPanel,黑色方块是bottomGridJPanel,白色圆圈代表JLabel内的玩家图像。蓝色圆圈代表一个视口,用户将通过它来查看游戏,并且是我希望玩家图标居中的位置。目前,用户可以使用视口周围区域中非常不雅的按钮来移动网格。这可能就足够了,但在游戏开始时,玩家必须四处移动网格,直到找到他们的图标。
【问题讨论】:
-
一些示例代码会很好
-
+1 表示更新;它让我想起了旧的AppleTrek。