我有一个非常奇怪的问题,我正在制作的JPanel每次都不会更新。这是我用来更新包含我游戏地图的JPanel的方法。调用MapView会在其中创建一个带有地图的JPanel。但是,有时地图会刷新,其中的所有图块都会正确显示,有时它只显示右上角的图块。
public void updateMap(char[][] map){
remove(mapView);
revalidate();
repaint();
mapView = new MapView(logic, oCreator, 240, 240, map);
mapView.setBounds(40, 80, 240, 240);
add(mapView);
}
MapPanel类中绘制地图的方法:
public JPanel addMapPanel(char[][] map){
int mapLength = map.length;
int mapHeight = map[0].length;
int tileSize = Math.min((length / mapLength), (height / mapHeight));
absoluteMapHeight = tileSize * mapHeight;
absoluteMapLength = tileSize * mapLength;
JPanel mapFrame = new JPanel(new GridLayout(mapHeight, mapLength));
mapFrame.setBackground(oCreator.getColorMedium());
int counter = 0;
for(int yIndex = 0; yIndex < mapHeight; yIndex++){
for(int xIndex = 0; xIndex < mapLength; xIndex++){
char charAtPos = map[xIndex][yIndex];
JPanel tile;
//A tile is just a JPanel with the correct background.
switch(charAtPos){
//TODO Colours are placeholders.
case '.':
tile = createMapTile(Color.DARK_GRAY, tileSize);
break;
case '#':
tile = createMapTile(Color.black, tileSize);
break;
case 'G':
tile = createMapTile(Color.yellow, tileSize);
break;
case 'P':
tile = createMapTile(Color.MAGENTA, tileSize);
break;
case 'E':
tile = createMapTile(Color.RED, tileSize);
break;
default:
tile = createMapTile(Color.blue, tileSize);
}
mapFrame.add(tile);
counter++;
}
}
System.out.println(counter);
return mapFrame;
}
有时它会画出这个:http://puu.sh/7Xcxo.png
有时它会绘制整个地图:http://puu.sh/7XcAm.png
我不确定为什么。