0

How do I use GridLayout to make rows with varying heights?

I want to have a table-like structure with two columns and a variable number of rows which will increase with time. In each row, the two cells should have the same height, but different rows should have different heights, depending on the text.

This is what I have:

JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createLineBorder(Color.BLACK);
for (int i = 0; i < 20; i++) {
    JTextArea left = new JTextArea("Left " + i);
    JTextArea right = new JTextArea("Right " + i);
    left.setBorder(BorderFactory.createCompoundBorder(border,
            BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    right.setBorder(BorderFactory.createCompoundBorder(border,
            BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    JPanel p = new JPanel(new GridLayout(1,2));
    p.add(left);
    p.add(right);
    panel.add(p);
}

The problem is that when I add text that needs a greater height (example below), then all rows increase in height to keep the row heights uniform amoing all rows.

JTextArea left = new JTextArea("Left\nA\nB\nC\nD");
JTextArea right = new JTextArea("Right\nA\nB\nC\nD");
left.setBorder(BorderFactory.createCompoundBorder(border,
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
right.setBorder(BorderFactory.createCompoundBorder(border,
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
JPanel p = new JPanel(new GridLayout(1,2));
p.add(left);
p.add(right);
panel.add(p);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Software Dev
  • 910
  • 3
  • 10
  • 27
  • 3
    If you want a table-like structure, use a `JTable`. A `GridLayout` makes all the grid blocks the same size. You might be able to use a `GridBagLayout`. – Gilbert Le Blanc Nov 23 '21 at 14:16
  • This could be useful to you: https://stackoverflow.com/questions/15853720/setting-the-height-of-a-row-in-a-jtable-in-java – ControlAltDel Nov 23 '21 at 14:24

0 Answers0