ksm001
ksm001

Reputation: 4022

how to add manually a label with a text field inside a panel using Java

I have a dialog and inside this dialog I have a list on the left and on the right I have a panel

I created these things using the gui builder of netbeans

now for the panel, I have 3 pairs of label - textfield

the problem is that depending on the user's input the pairs may become 4, or 5 etc

so I can't just draw these pairs using the gui builder, I need to create them by writing code

the question is, what kind of layout for this panel should I use in order to achieve this?

the panel is like that

label1 textfield
label2 textfield
label3 textfield
empty
empty
etc

here's a picture:

thanks

Upvotes: 0

Views: 2738

Answers (1)

Howard
Howard

Reputation: 39207

Personally I prefer a GroupLayout for such tasks.

Screenshot for below GroupLayout

GroupLayout layout = new GroupLayout(container);
container.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);

Group groupLabels = layout.createParallelGroup();
Group groupFields = layout.createParallelGroup();
Group groupRows = layout.createSequentialGroup();

layout.setHorizontalGroup(layout.createSequentialGroup()
    .addGroup(groupLabels)
    .addGroup(groupFields));
layout.setVerticalGroup(groupRows);

for (int i = 0; i < 5; i++) {
    JLabel label = new JLabel("ABCDEFGHIJ".substring(0, 2 + 2 * i));
    JTextField field = new JTextField("ABCDEFGHIJ".substring(0, 2 + 2 * i));

    groupLabels.addComponent(label);
    groupFields.addComponent(field);
    groupRows.addGroup(layout.createParallelGroup()
        .addComponent(label)
        .addComponent(field, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE));
}

If you want to dynamically add more rows the only thing you have to do is to add the corresponding components to the three groups and call validate on the container.

Upvotes: 2

Related Questions