How about you read the Laying Out Components Within a Container tutorial first? I abuse this saying but, there's always more than one way to skin a cat
Here's a superfluous example that uses BoxLayout
and setAlignmentX(...)
on the JComponent
instances -
public final class StackComponentsDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class DisabledJButton extends JButton{
public DisabledJButton(){
super("Disabled");
setEnabled(false);
setAlignmentX(Component.CENTER_ALIGNMENT);
}
}
}
