EDIT :
Ok, I found out why.
My getX and getY were overriding the Component ones. So my output was like 1 pixel wise… Should have thought of that earlier.
Thanks to those who tried to help me !
Original Question :
I have this Board class which inherits from JPanel which is supposed to display a board (seriously) composed of Squares which are black or white labels. I’m using a GridLayout but when I launch the application (after putting my JPanel in some dummy JFrame) the JLabels appear to be stacked on top of each other in the left hand corner which is not what I want. However the mouse listener seems to behave correctly since I get the good coordinates and the labels’ color toggle between black and white.
Here is the code :
public class Board extends JPanel {
private int dimx,dimy;
private Square[][] squares;
public Board(int x, int y){
super();
this.setLayout(new GridLayout(x,y));
dimx = x;
dimy = y;
squares = new Square[dimx][dimy];
for(int i=0; i<dimx; i++){
for(int j=0; j<dimy; j++){
Square sq = new Square(i,j);
squares[i][j] = sq;
this.add(sq);
sq.addMouseListener(new SquareListener(i,j,this));
}
}
}
public Square[][] getSquares() {
return squares;
}
}
public class Square extends JLabel {
private boolean black;
private int x,y;
private char c;
public Square(int x, int y){
super();
setBackground(Color.WHITE);
Border blackline = BorderFactory.createLineBorder(Color.black);
setBorder(blackline);
setOpaque(true);
setHorizontalAlignment(JLabel.CENTER);
this.x = x;
this.y =y;
c = ' ';
}
public void toggle(){
black = !black;
}
public boolean isBlack(){
return black;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
if(isBlack()){
setBackground(Color.BLACK);
}
else{
setBackground(Color.WHITE);
}
}
}
public class SquareListener implements MouseListener{
private int x,y;
private Board board;
public SquareListener(int x, int y, Board b){
this.x = x;
this.y = y;
this.board = b;
}
@Override
public void mouseClicked(MouseEvent arg0) {
board.getSquares()[x][y].toggle();
board.repaint();
System.out.println("Clicked on "+x+","+y);
}
You shouldn’t change the background color inside the
paintComponent()method. You shouldn’t even have apaintComponent()method. And you also shouldn’t have to callrepaint(). Yourtoggle()method should be the one that changes the background:Finally, the
getX()andgetY()methods override methods from JComponent. Choose another name for these methods.