17

I need to position a JLabel over some JButtons, vertically, like a game menu. They should all be centered. I already downloaded MigLayout, but I'm not sure how to use that, so I just want a way to position my components vertically and centered, MigLayout or not. Also, I don't want to use a IDE GUI designer.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
Jimmt
  • 782
  • 2
  • 9
  • 28
  • 2
    *"I don't want to use a IDE GUI designer"* +1 :) Such designers *can* increase productivity for a developer that already understands the layouts and how to combine them. Until you become proficient in core J2SE layouts (+ perhaps a 3rd party layout or 3) it is less than helpful to be trying to design a GUI while fighting the GUI designer. – Andrew Thompson Jan 21 '12 at 05:35
  • 2
    The problem is, I already wrote all my GUI stuff by hand (except for this), and I don't want to revise it will provide a big benefit. – Jimmt Jan 21 '12 at 23:24

2 Answers2

28

You might use a (single column) GridLayout or BoxLayout for this. See Using Layout Managers & A Visual Guide to Layout Managers for more tips, ideas and working source.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
9

You should use BoxLayout. Here a basic example

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class VerticalPanel extends JPanel {

    public VerticalPanel() {
        super();
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        for (int i = 0; i < 10; i++) {
            add(new JLabel("Label n°" + i));
        }
    }

}
RousseauAlexandre
  • 1,484
  • 19
  • 24