はい、基本的に、これまでのところ:
- カスタムJFrame(ApplicationWindow)を作成するメインクラス。
- JFrameを拡張し、ウィンドウとして機能するApplicationWindowクラス。
- JPanelを拡張し、(GridLayoutを使用して)以下の8x8グリッドを表示するためのMapDisplayPanelクラス。
- JPanelを拡張するMapBlockクラス。
- MapBlocksは、ゲームデータを格納するクラスGameData.javaに含まれています。
画面に描画されるMapBlockが1つだけであることを除いて、すべてが機能しているようです。
コード:
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が呼び出されているようです。これが私の出力の写真です:
助けてください!!
回答:
回答№1は4あなたは上書きしています getX
そして getY
に MapBlock
コンポーネントのすべてのインスタンスを配置するためにレイアウトマネージャによって使用されています
public int getX() {
return xPos;
}
public int getY() {
return yPos;
}
それらを削除するか、メソッドの名前を変更してください。