I ran into 2 other problems. But let me explain one by one.
First I tried to center 3 Buttons with the BoxLayout in the middle of a jframe with the same distance to each button by using Box.createVerticalGlue() and Box.createRigidArea():
panel.add(Box.createVerticalGlue());
panel.add(Box.createRigidArea(new Dimension(0, 100)));
panel.add(DrawSysButton);
panel.add(Box.createRigidArea(new Dimension(0, 195)));
panel.add(PickBanButton);
panel.add(Box.createRigidArea(new Dimension(0, 195)));
panel.add(ExitButton);
panel.add(Box.createRigidArea(new Dimension(0, 100)));
panel.add(Box.createVerticalGlue());
As soon as I put this into the code, the buttons look like this:
The buttons are cut off on the right side and the distance between Button 1 and 2 seems to be not the same as between Button 2 and Close.
When I remove the Glue and RidigAreas, then the buttons are just in the top center of the frame with many empty space beneath:
I tried a few things to fix that, but nothing helped. Maybe you can help me. I´ll put down here the whole code you need to run this problem by yourself. I tried to create it as minimal as it´s possible.
Thanks in Advance.
import javax.swing.*;
import java.awt.*;
public class main extends JFrame {
//this method loads the first screen that the user sees
public void frameLoader() {
setTitle("3 Centered Buttons");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
//Setting up all buttons and panels we need later on
JPanel panel = new JPanel();
//The Draw-System one
JButton DrawSysButton = new JButton("Button 1");
DrawSysButton.setFocusPainted(false);
DrawSysButton.setPreferredSize(new Dimension(120, 30));
//The Pick&Ban one
JButton PickBanButton = new JButton("Button 2");
PickBanButton.setFocusPainted(false);
PickBanButton.setPreferredSize(new Dimension(120, 30));
//The Exit one
JButton ExitButton = new JButton("Close");
ExitButton.setPreferredSize(new Dimension(120, 30));
//Adding all buttons to the panel
panel.add(Box.createVerticalGlue());
panel.add(Box.createRigidArea(new Dimension(0, 100)));
panel.add(DrawSysButton);
panel.add(Box.createRigidArea(new Dimension(0, 195)));
panel.add(PickBanButton);
panel.add(Box.createRigidArea(new Dimension(0, 195)));
panel.add(ExitButton);
panel.add(Box.createRigidArea(new Dimension(0, 100)));
panel.add(Box.createVerticalGlue());
//set the Frame visible & add the panel to the frame
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setPreferredSize(new Dimension(120, 500));
panel.setMaximumSize(new Dimension(120, 500));
getContentPane().add(panel);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
//building the Start-Screen
main StartScreen = new main();
StartScreen.frameLoader();
}
}