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);
}
}
JButton buttonOkNotification = new JButton("OK");
//buttonOkNotification.setHorizontalAlignment(JLabel.CENTER); // does not do anything
//buttonOkNotification.setAlignmentX(Component.CENTER_ALIGNMENT); // does not do anything
Note that the methods being called on the button are to align the content of the button, not the button itself. These constraints usually only become relevant or noticeable if the component is stretched larger then its preferred size. That stretching is usually as a result of the layout and constraint of the container that it resides in. A good example is a BorderLayout
:
PAGE_START
or PAGE_END
.LINE_START
or LINE_END
.CENTER
.Contrast that with a FlowLayout
. The flow layout does not stretch components vertically or horizontally, instead always keeping them at their preferred size.
To align the button component within the panel, it is necessary to use constraints to the layout. That can be done on construction, e.g.:
new FlowLayout(FlowLayout.RIGHT); // aligns all child components to the right hand side
But is more commonly done when adding a component to a container. E.G. on adding a component to a GridBagLayout
, it might look like this:
gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
panel.add(new JLabel("North West"), gridBagConstraints);