How to add buttons and other components dynamically with a free layout in a swing?

Hi, I am new to java swing. I have to add buttons dynamically, when I try to add these buttons dynamically, it is not added to the panel when it is in the free layout. It accepts any layout as a zero layout or gridbaglayout.

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

+3
source share
1 answer

I assume that with the “free layout” you are referring to the Free Design layout, also called GroupLayout, developed by Netbeans. The main idea of ​​this layout is the convenience that it offers when interactively designing and adding components with simple visual support using graphic designers.

The GUI constructor generates the necessary code that supports the proper placement of components. Here is the automatically generated code to host 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 simple interactive placement is transferred to the received code. This makes this layout not very suitable for processing dynamic components.

FlowLayout GridLayout . FlowLayout JPanel GroupLayout JPanel, .

+4

All Articles