Search code examples
javaswingjpanellayout-managerflowlayout

How can I manually place components in a FlowLayout or a GridLayout?


I am having trouble deciding which layout to use on a JPanel. I need the JPanel to look something like what I have attempted to draw here.

|-----------------------|
|       Some JLabel     |
|                       |
|  JLabel |JTextField|  |
|  JLabel |JTextField|  |
|  JLabel |JTextField|  |
|-----------------------|

I was thinking about using FlowLayout but I can't figure out how to manually set a component to be on the next row. I tried GridLayout and I have had some success but not quite what I was looking for. Here is the code for this JPanel I have so far if it helps.

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(4, 1));
JLabel description = new JLabel("description..");

JLabel label1 = new JLabel("label1");
JLabel label2 = new JLabel("label2");
JLabel label3 = new JLabel("label3");       

JTextField field1 = new JTextField(25);
JTextField field2 = new JTextField(25);
JTextField field3 = new JTextField(25);

mainPanel.add(description);
mainPanel.add(label1);
mainPanel.add(field1);
mainPanel.add(label2);
mainPanel.add(field2);
mainPanel.add(label3);
mainPanel.add(field3);

Thanks!


Solution

  • You could use a GridBagLayout to achieve this, but it might be eaiser to simple use a BorderLayout, placing the title in the NORTH position and placing another panel with the fields on it, using a GridLayout in the CENTER position.

    Of course, the final result will come down to what you want.

    Have a look at A Visual Guide to Layout Managers for some more ideas and don't be afraid to use compound layouts