[英]Extended JPanel ruins GridLayout
我想要像這樣修改我的JPanel:
public class Square extends JPanel {
private Checker fromChecker;
private int x;
private int y;
Square(int x, int y){
this.x = x;
this.y = y;
}
public int getX(){ return this.x; }
public int getY(){ return this.y; }
void setPossibleMoveChecker(Checker fromChecker){ this.fromChecker = fromChecker; }
Checker getPossibleMoveChecker(){ return this.fromChecker; }
}
我在這里打電話給Square
:
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(Game.grid_size, Game.grid_size));
for(int x=1; x <= Game.grid_size; x ++){
for(int y=1; y <= Game.grid_size; y ++) {
Square square = new Square(x, y);
// grid colour
Color square_color = Game.grid1_colour;
if((x + y) % 2 == 0){
square_color = Game.grid2_colour;
}
square.setBackground(square_color);
square.addMouseListener(new Mouse());
panel.add(square);
}
}
不幸的是,這就像:
好像我換線了:
Square square = new Square(x, y);
至
JPanel square = new JPanel();
它完美地像:
您正在覆蓋兩個關鍵的JComponent方法, getX()
和getY()
,這會弄亂組件的位置,因為這是布局管理器用於組件放置的關鍵行為之一。
解決方案: 重命名這些方法!
public class Square extends JPanel {
private Checker fromChecker;
private int column;
private int row;
Square(int column, int row){
this.column = column;
this.row = row;
}
public int getColumn(){
return this.column;
}
public int getRow(){
return this.row;
}
// ....
支持組合優於繼承的另一個原因,特別是在處理具有許多可能可重寫方法的復雜類時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.