好了,所以基本上,我到目前爲止有:的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