开发者

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

开发者 https://www.devze.com 2023-04-08 02:29 出处:网络
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

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开发者_C百科 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:

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

thanks


Personally I prefer a GroupLayout for such tasks.

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号