As an alternative, consider a nested layout . In the example below, the corresponding label is added to the SOUTH
a BorderLayout
, by default for JFrame
, and the extra sheet for your login panel is added to CENTER
. Examine the resizing behavior of each approach for suitability.
Addendum: I hope [to find out] why setAlignmentY()
ignored.
As stated in How to use BoxLayout features: Box layout options : "When BoxLayout
exposes components from top to bottom, ... any extra space appears at the bottom of the container." This explains your initial observation and correction.
In the API, note that setAlignmentX()
"Sets the vertical alignment" and setAlignmentY()
"Sets the horizontal alignment". In this context, vertical means the vertical axis of the layout from top to bottom, for example BoxLayout.Y_AXIS
, and horizontal means the horizontal axis of the layout from left to right, for example BoxLayout.X_AXIS
. In How to use BoxLayout: troubleshooting alignment problems , BoxAlignmentDemo
contrasts two. In the diagram from left to right, shown in the figure below, setAlignmentY()
used to adjust the vertical position relative to the horizontal layout axis. At the top, such as yours, setAlignmentY()
just doesn't work.
![setAlignmentY](https://fooobar.com/undefined)
![image](https://fooobar.com/undefined)
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Font; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class Test { private void display() { JFrame f = new JFrame("Test"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(createLogin(), BorderLayout.CENTER); JLabel admonition = new JLabel("ChatBytes™—Do not steal.", JLabel.CENTER); f.add(admonition, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } private static JPanel createLogin() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); JLabel label = new JLabel("Existing CHATBYTES login panel."); label.setFont(label.getFont().deriveFont(Font.ITALIC, 24f)); label.setAlignmentX(0.5f); label.setBorder(new EmptyBorder(0, 20, 0, 20)); p.add(Box.createVerticalStrut(36)); p.add(label); p.add(Box.createVerticalStrut(144)); return p; } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new Test().display(); } }); } }
source share