Search code examples
javaswinggridbaglayoutcardlayout

GridBagLayout misbehaving. Horizontal distribution problems


This is what I am trying to achieve:

   |--0--|--1--|--2--|--3--|--4--|--5--|--6--|--7--|--8--|--9--|
0  |     |JLabe|l----|-----|-----|-----|-----|-----|-----|-----|
1  |     |     |JLabe|l----|-----|-----|-----|-----|-----|-----|
2  |     |     |     |JLabe|l----|-----|-----|-----|-----|-----|
3  |     |     |     |JLabe|l----|-----|-----|-----|-----|-----|

This is what I have got so far, this is as close as I can get to what I am after.

        center.setLayout(centerLayout);
    JPanel[] card = new JPanel[1]; //update as it gets longer, eventually Scoreboard.LENGTH
    card[0] = new JPanel();
    GridBagLayout cardLayout = new GridBagLayout();
    card[0].setLayout(cardLayout);
    cardLayout.setConstraints(winner, new GridBagConstraints(0, 0, 10, 1, 1, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
    card[0].add(winner);
    cardLayout.setConstraints(name, new GridBagConstraints(1, 1, 9, 1, 0.8, 0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
    card[0].add(name);
    cardLayout.setConstraints(with, new GridBagConstraints(2, 2, 8, 1, 0.7, 0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
    card[0].add(with);
    cardLayout.setConstraints(score, new GridBagConstraints(2, 3, 8, 1, 0.7, 0, GridBagConstraints.LAST_LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
    card[0].add(score);
    center.add(card[0], "card1");
    this.getContentPane().add(center);

And for some reason it displays like this:

   |--0--|--1--|--2--|--3--|--4--|--5--|--6--|--7--|--8--|--9--|
0  |JLabe|l----|-----|-----|-----|-----|-----|-----|-----|-----|
1  |JLabe|l----|-----|-----|-----|-----|-----|-----|-----|-----|
2  |JLabe|l----|-----|-----|-----|-----|-----|-----|-----|-----|
3  |JLabe|l----|-----|-----|-----|-----|-----|-----|-----|-----|

Perhaps there is a more appropriate way to lay out my text than using GridBagLayout. (It does need to work on different resolutions, so which ever layout manager used needs to be flexible)


Solution

  • 1) Naming a GridBagLayout variable "cardLayout" is not the best idea, IMO.

    2) Since you only gave a code snippet and did not provide an SSCCE, I can only guess based solely on the "pictures" you gave. GridBagLayout needs a component in each row/column to define it's size. A given column will be as wide as the component with the widest preferred size found in that column. Same goes for height. So based on the picture of your results, no component that has a preferred width is in column 0. One workaround is to place a Box.createHorizontalStrut(someWidth) in the desired column.