There are several different commands to explicitly align elements in Java Swing. It appears that these commands only work under some extremely specific constraints and these constraints are not documented anywhere. Most of the time that I want to align elements, these commands don't do anything at all. So I'm wondering why do these commands not do what the documentation says that they do, and also, how to align elements in Swing?
For reference, here is a SSCCE with an OK button that aligns to the left when we explicitly set horizontal alignment to center.
import javax.swing.*;
import java.awt.*;
public class E {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel notificationView = new JPanel();
notificationView.setPreferredSize(new Dimension(300, 145));
notificationView.setLayout(new GridBagLayout());
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
JLabel notificationText = new JLabel("Here is some text to display to the user and below this is an ok button.");
content.add(notificationText);
JButton buttonOkNotification = new JButton("OK");
//buttonOkNotification.setHorizontalAlignment(JLabel.CENTER); // does not do anything
//buttonOkNotification.setAlignmentX(Component.CENTER_ALIGNMENT); // does not do anything
content.add(buttonOkNotification);
notificationView.add(content);
frame.add(notificationView);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}