私はSwingでチェスボードを描いています。私はタイル(jpanel)を作成し、ボードにコンポーネントを追加しようとしました(別のjpanel)。タイルが追加されるたびに、私は黒または白のいずれかの色を設定しようとしました。ボードにはGridLayoutがあります。ボードはそれに64のタイルを追加しますが、タイルの1つだけが色を取得し、残りはデフォルトの色を取得します。私はタイル(jpanel)をボタン(JButton)に変更しようとしました(コンポーネントがボードに追加されているかどうかを確認するため)、プログラムは64ボタンをボードに追加しました。だから私は、レイアウトやコンポーネントの追加に問題はないと思っていますが、むしろ色を更新することとは何か?JPanel内にあるJPanel要素に色付けする
もっと小さいJpanel(タイル)を大きなJpanel(ボード)に追加すると、どのように色を変更できますか?
次のようにプログラムが(着色スキームを気にしない、私は実際にチェスボードをしたくない)です:
class Tile extends JPanel{
private final int width = 50;
private final int height = 50;
Color tileColor;
int xPos, yPos;
public Tile(int xPos, int yPos, Color tileColor){
this.xPos = xPos;
this.yPos = yPos;
this.tileColor = tileColor;
}
public Dimension getPreferredSize(){
return new Dimension(width, height);
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(tileColor);
g.fillRect(xPos, yPos, getWidth(), getHeight());
}
}
class Board extends JPanel{
private final int width = 400;
private final int height = 400;
private int numTiles = 8;
private final Color black = Color.BLACK;
private final Color white = Color.WHITE;
private final int hGap = 2;
private final int vGap = 2;
public Board(){
setLayout(new GridLayout(numTiles, numTiles,hGap, vGap));
setBackground(Color.CYAN);
Color tileColor;
int yPos = 0;
for(int i = 0; i < numTiles; i++){
int xPos = 0;
for(int j = 0; j < numTiles; j++){
if(j % 2 == 0)
tileColor = black;
else
tileColor = white;
add(new Tile(xPos, yPos, tileColor));
xPos += 50;
}
yPos += 50;
}
}
public Dimension getPreferredSize(){
return new Dimension(width,height);
}
}