How can vertical alignment be achieved in a Swing layout?
In Swing layout, BoxLayout can be used to achieve vertical alignment.
First, create a JPanel as a container and set its layout manager to BoxLayout.
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Next, create components that need to be aligned vertically, such as JLabel, JTextField, and add them to the container.
JLabel label = new JLabel("Label");
JTextField textField = new JTextField(10);
panel.add(label);
panel.add(textField);
By default, BoxLayout aligns components in the vertical direction. To align them top or bottom, you can set the alignment of the components. Use the setAlignmentX method to set the horizontal alignment of the components, and use the setAlignmentY method to set the vertical alignment of the components.
For example, to align the components vertically, you can use the following code:
label.setAlignmentY(Component.TOP_ALIGNMENT);
textField.setAlignmentY(Component.TOP_ALIGNMENT);
Finally, add the container to the window for display.
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setVisible(true);
In this way, the layout with aligned top and bottom is achieved.