Bagdan
Bagdan

Reputation: 13

Buttons in GridLayout, non resize

I have problems with GridLayout because I understand that I need this only for solving my problem: I need this matrix panel (made in GridLayout) to be non resizable. Like a whole square that is, for example, in the middle and can not be resized. I have made a lot of research work and I couldn't find an answer.

public class  ButtonsMatrix extends JButton {

    private int[][] fModel;
    private  int fX;
    private  int fY;

    public ButtonsMatrix(int x, int y, int[][] model) {

        fX = x;
        fY = y;
        fModel = model;

        addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fModel[fX][fY] = fModel[fX][fY] == 1 ? 0 : 1;
                updateNameFromModel();
            }
        });
        updateNameFromModel();
    }

    private void updateNameFromModel() {
        setText(String.valueOf(fModel[fX][fY]));
    }

    public static void main(String[] args) {

        int dim=10;
        int matrix[][] = new int[10][10];

        JFrame f = new JFrame("Window containing a matrix");
        JPanel p = new JPanel();
        JPanel extra = new JPanel(new FlowLayout());
        extra.add(p);
        p.setLayout(new GridLayout(dim, dim));

        for (int r = 0; r < dim; r++){
            for (int c = 0; c < dim; c++){
                ButtonsMatrix button= new ButtonsMatrix(r, c, matrix);
                p.add(button);
            }
        }

        f.add(p);
        f.pack();
        f.setVisible(true);
    }
}

Upvotes: 1

Views: 856

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168835

Put the panel with a GridLayout inside another panel that has a GridBagLayout.

If it's the only component and is added with no GridBagConstraints, it will be centered and its size will be constant irrespective of the size assigned to the panel with grid bag layout.

Edit

The above code adds the panel containing a grid layout of buttons to the extra panel defined in the main method (which has a FlowLayout). This will also work to keep the button matrix panel at its preferred size.

The problem with the code is that it thereafter ignores the extra panel and adds the p panel (with the grid layout of buttons) directly to a JFrame with a (default) BorderLayout. Doing so results in the p panel being added to the CENTER of the border layout, which will stretch a component to fill the available width and height.

To fix that, simply change:

f.add(p);

To:

f.add(extra);

Upvotes: 1

Related Questions