[英]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.