编辑:好的,我找到了原因。
我的 getX 和 getY 覆盖了组件。所以我的输出就像 1 像素明智......应该早点想到这一点。
感谢那些试图帮助我的人!
原始问题:
我有这个继承自 JPanel 的 Board 类,它应该显示一个由黑色或白色标签的 Squares 组成的板(严重)。我正在使用 GridLayout 但是当我启动应用程序时(在将我的 JPanel 放入一些虚拟 JFrame 之后),JLabels 似乎在左手角堆叠在一起,这不是我想要的。然而,鼠标侦听器似乎表现正确,因为我得到了良好的坐标并且标签的颜色在黑白之间切换。
这是代码:
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);
}