编辑: 好的,我知道原因了。
我的 getX 和 getY 覆盖了组件的。所以我的输出就像 1 个像素...应该早点想到这一点。
感谢那些试图帮助我的人!
原始问题:
我有一个继承自 JPanel 的 Board 类,它应该显示一个由黑色或白色标签的方 block 组成的板(认真地)。我正在使用 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 中的方法。为这些方法选择另一个名称。
关于java - JPanel 中 JLabels 显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10996462/