在 JPanel 中错误地显示 JLabels



>编辑:好的,我找到了原因。

我的 getX 和 getY 覆盖了组件。所以我的输出就像 1 像素一样......应该早点想到的。

感谢那些试图帮助我的人!

原始问题 :

我有一个从 JPanel 继承的 Board 类,它应该显示一个由黑色或白色标签的正方形组成的板(认真)。我正在使用 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);
}

不应更改 paintComponent() 方法中的背景颜色。你甚至不应该有一个paintComponent()的方法。而且您也不必打电话给repaint().您的toggle()方法应该是更改背景的方法:

public void toggle(){
    black = !black;
    setBackGround(black ? Color.BLACK : Color.WHITE);
}

最后,getX()getY() 方法覆盖 JComponent 中的方法。为这些方法选择其他名称。

好的,我找到了原因。

我的 getX 和 getY 覆盖了组件。所以我的输出就像 1 个像素而不是 1 个正方形......应该早点想到的。

感谢那些试图帮助我的人!

最新更新