简体   繁体   中英

Extended JPanel ruins GridLayout

I am wanting to modify my JPanel like this:

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; }
}

and I call Square here:

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);
    }
}

Unfortunately this comes out like:

在此输入图像描述

Where as if I change the line:

Square square = new Square(x, y);

to

JPanel square = new JPanel();

it comes out perfectly like:

在此输入图像描述

You're overriding two key JComponent methods, getX() and getY() , and this is messing with the placement of components since this is one of the key behaviors the layout managers use for component placement.

Solution: Re-name those methods!

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; 
    }

    // ....

Yet another reason to favor composition over inheritance, especially when dealing with complex classes that have many potentially overrideable methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM