編輯: 好的,我發現了原因。Jaabel在JPanel中的顯示不正確
我的getX和getY重寫了組件的。所以我的輸出像是1像素明智的...應該早點想到這一點。
感謝那些試圖幫助我的人!
原題:
我有這個局級從JPanel的繼承這應該顯示板(嚴重)廣場它們是黑色或白色的標籤組成。我使用的是GridLayout,但是當我啓動應用程序時(將我的JPanel放在一些虛擬的JFrame中之後),JLabel似乎在左下角堆疊在一起,這不是我想要的。然而,鼠標監聽器似乎行爲正確,因爲我得到了良好的座標和黑白之間的標籤顏色切換。
下面是代碼:
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);
}
爲了更好地提供幫助,請發佈[SSCCE](http://sscce.org/)。 –
考慮發佈您的'解決方案'作爲答案並接受該答案。這在概述中清楚地表明瞭這個問題得到了回答。 [FAQ](http://stackoverflow.com/faq#questions)聲明可以回答你自己的問題 – Robin