好了,所以基本上,我到目前为止有:的Java AWT/Swing的:问题的paintComponent定制的JPanel(S)
- 用于创建自定义的JFrame(ApplicationWindow)主类。
- 一个扩展JFrame并充当窗口的ApplicationWindow类。
- 一个扩展JPanel的MapDisplayPanel类,用于(使用GridLayout)显示一个8x8格:
- 扩展JPanel的MapBlock类。
- MapBlocks都包含在一个类中包含游戏数据,GameData.java
这一切似乎工作,但只有一个MapBlock绘制到屏幕上。
代码:
Main.java
public class Main {
public static void main(String[] args) {
final ApplicationWindow window = new ApplicationWindow();
window.setVisible(true);
}
}
ApplicationWindow.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。这里是我的输出的照片:
请帮助!
就目前而言,你的'paintComponent'没有做任何事情来改变面板的背景颜色,并添加一个'LineBorer'无法实现。我认为这是测试代码,您将为'MapBlock#paintComponent'添加更多功能... – MadProgrammer 2013-05-12 23:41:14
1)为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 2)对代码块使用一致的逻辑缩进。代码的缩进旨在帮助人们理解程序流程。 3)不要设置顶级容器的大小。而是布置内容并调用'pack()'。 4)不要延长框架或其他顶层容器。而是创建并使用一个实例。 5)对于帧定位,你不能通过'setLocationByPlatform(true)'去。查看[这个答案](http://stackoverflow.com/a/7143398/418556)进行演示。 – 2013-05-13 04:30:43