1
votes

I have a panel that generates from a document. I don't know exactly how many fields and labels I'll be adding, and I want it to make two columns of label and field. How I think I can do this is with GridBagLayout and getting the GridBagConstraints, but I can't figure out how to do that. Anyone know how to get the GridBagConstraints back out of a JPanel/JFrame?

If not, any alternatives you can suggest would be greatly appreciated.

1

1 Answers

4
votes

I have a panel that generates from a document. I don't know exactly how many fields and labels I'll be adding, and I want it to make two columns of label and field. How I think I can do this is with GridBagLayout and getting the GridBagConstraints, but I can't figure out how to do that. Anyone know how to get the GridBagConstraints back out of a JPanel/JFrame?

  • you would need to loop inside Components added to container

  • take currenet layout to the temporary variable (I assumned there are JLabels and JTextFields placed into JPanel)

e.g.

Component[] comps = panel.getComponents();
GridBagLayout layout =  (GridBagLayout) panel.getLayout();

for (int i = 0; i < comps.length; ++i) {
    Component comp = comps[i];
    GridBagConstraints gbc = layout.getConstraints(comp);
    System.out.println("Component : " + comp + " , with GBC: " + gbc);
}
  • then very simple, similar way is possible to remove some JComponent from Container and replace with a new...

any alternatives you can suggest would be greatly appreciated.

  • use JTable for variable amount of columns and rows