好的,基本上,到目前为止,我所拥有的:


创建自定义JFrame(ApplicationWindow)的主类。
一个ApplicationWindow类,它扩展JFrame并充当窗口。
一个MapDisplayPanel类,该类扩展了JPanel并旨在(使用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。这是我的输出的图片:

http://imgur.com/vxGAIEL

请帮忙!!

最佳答案

您正在覆盖getXgetYMapBlock中,而布局管理器正在使用和来放置组件的所有实例

public int getX() {
   return xPos;
}

public int getY() {
   return yPos;
}


删除它们或重命名方法。

关于java - Java AWT/Swing:自定义JPanel的paintComponent问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16512944/

10-10 10:18