3

Hi i am new to java swing. i have to add buttons dynamically , when i try to add those buttons dynamically it does not add to panel when it is in free layout. it accepts any one layout like null layout or gridbaglayout.

Is there any other way to add components dynamically with free layout?

Voqus
  • 159
  • 1
  • 11
Babu R
  • 1,025
  • 8
  • 20
  • 40
  • 1
    What is free layout? How do you add your components. We don't have any crystal ball. Provide an SSCCE. – JB Nizet May 04 '12 at 07:54

1 Answers1

4

I assume that with "free layout", you are referring to the Free Design Layout, also called GroupLayout developed by Netbeans. The basic idea behind this layout is the convenience it offers when designing interactively and adding components with simple visual support using GUI builders.

The GUI builder generates the necessary code that supports the correct placement of the components. Here is the automatically generated code for placing two JButtons on a JPanel with Free Design Layout:

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton1)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 217, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(96, 96, 96))))
);
layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jButton1)
        .addGap(100, 100, 100)
        .addComponent(jButton2)
        .addContainerGap(140, Short.MAX_VALUE))
);

As you can see the cost of easy interactive placement is passed on to the resulting code. This makes this layout not really suitable for dynamic component handling.

On the other hand FlowLayout or GridLayout allow you to deal with dynamic components programmatically better. You can also always add a FlowLayout JPanel to a GroupLayout JPanel, in order to get the best of both layouts.

Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47