How to align things in GroupLayout?

1.1k views Asked by At

I have to make this Panel using GroupLayout, I have written the following code for it

GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);

layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);

layout.setHorizontalGroup(layout
  .createSequentialGroup()
  .addComponent(label)
  .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
              .addComponent(installButton).addComponent(installProgressBar)
              .addComponent(upadteLabel).addComponent(upadteButton)
              .addComponent(removeButton)));

layout.setVerticalGroup(layout
  .createParallelGroup()
  .addComponent(label)
  .addGroup(layout
              .createSequentialGroup()
              .addComponent(installButton)
              .addGroup(layout.createParallelGroup()
                          .addComponent(installProgressBar)
                          .addComponent(upadteLabel))
              .addComponent(upadteButton).addComponent(removeButton)));

layout.linkSize(SwingConstants.HORIZONTAL, installButton,
                installProgressBar, upadteLabel, upadteButton, removeButton);

The installProgressBar and updateLabel have to share the same space(done).

But this is not making the buttons right alinged, i have tries using GroupLayout.Alignment.TRAILING in various places but was unable to get it working. \Basically i want the label to be of fix size(i can do that) and the label is to be left aligned while the buttons have to be right aligned.

Can somebody help me out and also explain how the alignment works.

1

There are 1 answers

0
Akarshit Wal On BEST ANSWER

To answer my own question adding a preferredGap() does the trick. The final code is

layout.setHorizontalGroup(layout
  .createSequentialGroup()
  .addComponent(label, labelWidth, labelWidth, labelWidth)
  .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
                   GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
  .addGroup(layout
              .createParallelGroup(GroupLayout.Alignment.CENTER)
              .addComponent(installButton, BUTTON_WIDTH, BUTTON_WIDTH,
                            BUTTON_WIDTH).addComponent(installProgressBar)
              .addComponent(updateLabel).addComponent(updateButton)
              .addComponent(removeButton)));

layout.setVerticalGroup(layout
  .createParallelGroup()
  .addComponent(label)
  .addGroup(layout
              .createSequentialGroup()
              .addComponent(installButton)
              .addGroup(layout.createParallelGroup()
                          .addComponent(installProgressBar)
                          .addComponent(updateLabel))
              .addComponent(updateButton).addComponent(removeButton)));

layout
  .linkSize(SwingConstants.HORIZONTAL, installButton, installProgressBar,
            updateLabel, updateButton, removeButton);