JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); JButton button1 = new JButton("Button 1"); panel.add(button1); JButton button2 = new JButton("Button 2"); panel.add(button2); panel.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); JLabel label1 = new JLabel("Name:"); panel.add(label1); JTextField textField1 = new JTextField(); panel.add(textField1); panel.setAlignmentX(Component.LEFT_ALIGNMENT);In this example, a label and a text field are added to the panel, and the setAlignmentX method is called with a value of Component.LEFT_ALIGNMENT, which aligns the components to the left. Both examples use the java.awt.event and java.awt packages.