好的,基本上,我到目前为止所拥有的:
- 创建自定义 JFrame (ApplicationWindow) 的主类。
- 扩展 JFrame 并充当窗口的 ApplicationWindow 类。
- 扩展 JPanel 的 MapDisplayPanel 类,旨在(使用 GridLayout)显示 8x8 网格:
- 扩展 JPanel 的 MapBlock 类。
- MapBlocks 包含在一个包含游戏数据的类 GameData.java 中
这一切似乎都有效,除了只有一个 MapBlock 被绘制到屏幕上。
代码:
主.java
public class Main {
public static void main(String[] args) {
final ApplicationWindow window = new ApplicationWindow();
window.setVisible(true);
}
}
应用程序窗口.java
public class ApplicationWindow extends JFrame {
public ApplicationWindow()
{
setTitle("Heroes!");
setLocationRelativeTo(null);
setSize(800,600);
// setLayout(new BorderLayout());
JPanel map = new MapDisplayPanel();
add(map);//, BorderLayout.CENTER);
}
}
MapDisplayPanel.java
public class MapDisplayPanel extends JPanel{
GameData game = null;
public MapDisplayPanel()
{
game = new GameData();
setLayout(new GridLayout(game.getWidth(),game.getHeight()));
setBackground(Color.CYAN);
MapBlock[][] map = game.getMap();
for(MapBlock[] aBlk : map)
{
for(MapBlock blk : aBlk)
{
if(blk != null){add(blk);}
}
}
}
}
MapBlock.java
public class MapBlock extends JPanel{
private int xPos = -1, yPos = -1;
//Constructors
public MapBlock(int x, int y, int terrain)
{
this.xPos = x;
this.yPos = y;
this.terrain = terrain;
setPreferredSize(new Dimension(50,50));
}
//Methods
@Override
public void paintComponent(Graphics g)
{
//setBackground(Color.GREEN);
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.MAGENTA);
g.fillRect(10, 10, this.getWidth() - 20, this.getHeight() - 20);
/*String out = Integer.toString(this.getX()) + Integer.toString(this.getY());
System.out.println(out); THIS WAS FOR DEBUG*/
}
//Accessors, mutators
public int getTerrain()
{return terrain;}
public int getX()
{return xPos;}
public int getY()
{return yPos;}
}
最后,GameData.java
public class GameData{
//Members
private MapBlock[][] map = null;
private int mapWidth = 8; private int mapHeight = 8;
//Constructors
public GameData()
{
map = new MapBlock[mapWidth][mapHeight];
for(int x = 0; x < mapWidth; x++)
{
for(int y = 0; y < mapHeight; y++)
{
map[x][y] = new MapBlock(x,y,1);
}
}
}
//Accessors, mutators
public MapBlock[][] getMap()
{return map;}
public int getWidth()
{return mapWidth;}
public int getHeight()
{return mapHeight;}
}
正如我所说,问题是只有左上角的 MapBlock 对象被绘制到屏幕上。我已经测试过这个核心,似乎所有组件都被正确添加,并且至少每个组件都调用了paintComponent。这是我的输出图片:
请帮忙!!