0

I am currently trying to add Jpanels to a horizontal group for a JpanelLayout. The number of custom JPanels added is defined by an int value (which will be defined by user). Im trying to add as many identical JPanels into the parent panel as required by the user. Currently i have tried defining a number of custom Jpanels, adding them to arraylist and then doing a for each loop, attempting to add them to the group, with no success. This is what the horizontal group layout code looks like:

// initialization of custom panels and adding them to arraylist for adding into horizontalgroup.
MatchPanel customPanel1 = new MatchPanel();
    MatchPanel customPanel2 = new MatchPanel();
    MatchPanel customPanel3 = new MatchPanel();

    ArrayList<MatchPanel>panels = new ArrayList<MatchPanel>();

    panels.add(customPanel1);
    panels.add(customPanel2);
    panels.add(customPanel3);

// Panel being initialized later in program        
 javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
    jPanel5.setLayout(jPanel5Layout);
    jPanel5Layout.setHorizontalGroup(
        jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel5Layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                for(MatchPanel p : panels) {
                .addComponent(p,javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                })
            .addContainerGap(82, Short.MAX_VALUE))
        .addGroup(jPanel5Layout.createSequentialGroup()
            .addGap(233, 233, 233)
            .addComponent(jLabel1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

Is there a way to define the HorizontalGroup and then add components to it using a function defined in the rest of the program, or is it simply a case of my syntax being wrong? If i can get this working i can transfer the method over to the verticalgroup as well.

Thanks for any help provided.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

2

this is a possible solution. I hope it helps.

Preview:

Preview of Group Layout with objects created at runtime

package sampleapp.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import static java.lang.Integer.parseInt;
import java.util.ArrayList;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

/**
 *
 * @author brianson
 */

public class GroupLayoutExample extends JFrame {
    private int elementsHeight;             //the height of all objects in the panel and the gaps between them
    private int numButtons;
    private ArrayList<JButton> btnArray;    //the array object that will hold the buttons created at runtime
    private JPanel panel;
    private JLabel label1;
    private JTextField textField1;
    private JButton button1;

    public GroupLayoutExample() {
        init();
    }

    public final void init(){
        //initiallize variables
        panel = new JPanel();
        elementsHeight = 22;                //initiallized with the value of 22 ie the size of the first and last container gaps
        label1 = new JLabel("Number of buttons");
        textField1 = new JTextField("");
        button1 = new JButton("Show Buttons");

        setPreferredSize(new Dimension(800, 600));
        setSize(800, 600);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        panel.setPreferredSize(new Dimension(101, 234));
        panel.setSize(101, 294);
        panel.setBackground(new Color(153, 153, 153));

        button1.addActionListener((e) -> {
            numButtons = parseInt(textField1.getText());
            if (numButtons > 1 && numButtons < 7) {
                if (panel.getComponentCount() > 0) {
                    panel.removeAll();
                }
                makeButtons(numButtons);
            }else{
                JOptionPane.showMessageDialog(null, "Number of buttons must be greater than 1 but less than 7");
            }
        });
        textField1.setBorder(new EmptyBorder(1, 10, 1, 1));

        //main window layout
        GroupLayout mainLayout = new GroupLayout(getContentPane());
        getContentPane().setLayout(mainLayout);
        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup()
            .addGroup(mainLayout.createSequentialGroup()
                .addContainerGap(202, Short.MAX_VALUE)
                .addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(mainLayout.createParallelGroup()
                    .addGroup(mainLayout.createSequentialGroup()
                        .addComponent(label1)
                        .addGap(18, 18, 18)
                        .addComponent(textField1, GroupLayout.PREFERRED_SIZE, 176, GroupLayout.PREFERRED_SIZE)
                    )
                    .addComponent(button1)
                )
                .addContainerGap(203, Short.MAX_VALUE)

            )
        );
        mainLayout.setVerticalGroup(mainLayout.createParallelGroup()
            .addGroup(mainLayout.createSequentialGroup()
                .addContainerGap(197, Short.MAX_VALUE)
                .addGroup(mainLayout.createParallelGroup()
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGroup(mainLayout.createSequentialGroup()
                        .addGroup(mainLayout.createParallelGroup()
                            .addComponent(label1, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
                            .addComponent(textField1, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
                        )
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(button1)
                    )
                )
                .addContainerGap(112, Short.MAX_VALUE)
            )
        );
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new GroupLayoutExample().setVisible(true);
        });
    }

    void makeButtons(int num){
        GroupLayout layout = new GroupLayout(panel);
        panel.setLayout(layout);

        //horizontal layout
        GroupLayout.ParallelGroup horizontalPara = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
        GroupLayout.ParallelGroup horizontalPara1 = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
        GroupLayout.SequentialGroup horizontalSeq = layout.createSequentialGroup();
        horizontalSeq.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
        btnArray = new ArrayList<>();
        for(int i = 0; i < numButtons; i++) {
            btnArray.add(new JButton(String.format("Button %d", i + 1)));
        }

        btnArray.forEach((btn) -> {
            horizontalPara1.addComponent(btn);
        });
        horizontalSeq.addGroup(horizontalPara1);
        horizontalSeq.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
        horizontalPara.addGroup(horizontalSeq);
        layout.setHorizontalGroup(horizontalPara);

        //Vertical layout
        GroupLayout.ParallelGroup verticalPara = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
        GroupLayout.SequentialGroup verticalSeq = layout.createSequentialGroup();
        verticalSeq.addContainerGap();
        elementsHeight += (btnArray.size() * 22);   //Adding the total height of buttons. Button default height is 22
        btnArray.forEach((btn) -> {
            verticalSeq.addComponent(btn);
            int i = (btnArray.size() - 1) - btnArray.indexOf(btn);
            //displayInfo(i + "", "Case ID");
            switch (i) {
                case 0:
                    verticalSeq.addContainerGap(11, Short.MAX_VALUE);
                    break;

                case 1:
                    int gapSize = panel.getHeight() - elementsHeight;       //Calculate size of gap so that the last component is placed at the bottom baseline
                    if (gapSize <= 0) {
                        gapSize = 11;
                    }
                    verticalSeq.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, gapSize, Short.MAX_VALUE);
                    break;

                default:
                    verticalSeq.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED);
                    elementsHeight += 11;       //The height for an unrelated component placement is 11
                    break;
            }
        });
        verticalPara.addGroup(verticalSeq);
        layout.setVerticalGroup(verticalPara);
    }
}

How it works: Firstly create variables for your various Group Layout orientations in this case, I have parallel and sequential groups. Add the objects that you create at runtime to the corresponding parallel and sequential groups depending on the layout you want to achieve. For more information on laying objects within these groups, refer to How to Use Group Layout(The Java™ Tutorials).

After you have added your components to the groups, set the horizontal and vertical layout groups to the appropriate parallel and sequential groups.

geek101
  • 21
  • 4