Search code examples
javaswinglayoutjlabelboxlayout

How to Center JButtons in a centered JLabel in a BoxLayout?


I'm new in Java GUI programming and I have a strange issue with the BoxLayout: I have an JLabel with an Icon. Added to the label are two JButtons. The Jlabel is placed in the CENTER position of the BorderLayout from a JFrame. Now I want that these two JButtons are always in the center of the JLabel even when I resize the JFrame. With setAlignmentX() the Jbuttons are centered horizontally , but there is no solution with setAlignmentY() for the vertical direction.

here is the code:

package footballQuestioner;

import java.awt.BorderLayout;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Houdini {

    public static void main(String[] args) {
        JFrame frame = new House();
    }

    }

    class House extends JFrame {

    private JLabel label = new JLabel(
            new ImageIcon(
                    "C:\\Users\\laudatio\\Documents\\Java\\MyProject\\src\\footballQuestioner\\footballfield.jpg")
            );
    private JButton one=new  JButton("one");
    private JButton two=new JButton("two");


    public House() {


        label.setLayout(new BoxLayout(label, BoxLayout.Y_AXIS));

        label.add(one);
        label.add(two);

        one.setAlignmentX(CENTER_ALIGNMENT);
        one.setAlignmentY(CENTER_ALIGNMENT);
        two.setAlignmentX(CENTER_ALIGNMENT);
        two.setAlignmentY(CENTER_ALIGNMENT);


        setLayout(new BorderLayout());
        setLocation(300, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(true);

        add(label,BorderLayout.CENTER);

        pack();
        setVisible(true);


    }

}

Please Help! :-((((


Solution

  • but there is no solution with setAlignmentY() for the vertical direction.

    Use "glue" before and after your two components. See the section from the Swing tutorial on How to Use Box Layout for more information and examples.

    Although MadProgrammers comment to use a GridBagLayout is an easier solution, but knowing about "glue" and "struts" can be helpful for customizing the layout of a BoxLayout.