Home > other >  Vertical alignment of a bottom panel
Vertical alignment of a bottom panel

Time:04-08

I want to vertically align 3 buttons in a bottom panel.

Here's what I wrote:

ClientWindow(){
    pickBtn = new JButton();
    attackBtn = new JButton();
    placeBtn = new JButton();
    
    JPanel userPanel = new JPanel();
    userPanel.setPreferredSize(new Dimension(100,100));
    userPanel.setBackground(Color.red);
    
    JFrame frame = new JFrame();
    frame.setTitle("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.setResizable(false);
    frame.setSize(1280,720);
    frame.setLocationRelativeTo(null);
    
    frame.add(userPanel,BorderLayout.SOUTH);
    
    userPanel.add(pickBtn);
    userPanel.add(attackBtn);
    userPanel.add(placeBtn);
    
    frame.setVisible(true);
}

How could I align them vertically?

CodePudding user response:

Take a look at enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JLabel label = new JLabel("This is just here to make some content");
                label.setBorder(new EmptyBorder(32, 32, 32, 32));

                JFrame frame = new JFrame();
                frame.add(label);
                frame.add(new UserPanel(), BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class UserPanel extends JPanel {

        public UserPanel() {
            JButton pickBtn = new JButton("Pick");
            JButton attackBtn = new JButton("Attack");
            JButton placeBtn = new JButton("Place");

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            add(pickBtn, gbc);
            add(attackBtn, gbc);
            add(placeBtn, gbc);
        }
    }
}
  • Related