I am drawing a chess board in Swing. I created tiles (jpanel) and then tried to add components to board(another jpanel). Each time a tile is added, i tried to set a color, either Black or White. Board has GridLayout. Board does add 64 tiles to it, but only one of the tiles get a color, the rest gets a default color. I tried changing tiles(jpanel) to buttons(JButton) (to see if components are added to board or not) and the program did add 64 buttons to the Board. So I am guessing there is no problem in layout and adding components,but rather something to do with updating the color?
So how can I change the color of these smaller jpanels(tiles) when I add them to the bigger Jpanel(Board)?
Program is as follows(don't mind the coloring scheme, i don't actually want a chess board):
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);
}
}
This is wrong:
g.fillRect(xPos, yPos, getWidth(), getHeight());
You're filling the color alright, but at xPos and yPos relative to this JPanel, meaning the color is way away from the JPanel's actual displayed region.
Solutions:
setBackground(...)
in the constructor.