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.
Asked
Active
Viewed 4.2k times
17
-
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
-
2The 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 Answers
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
-
@Jeffrey That was probably because I posted the reply before editing to add links. ;) – Andrew Thompson Jan 21 '12 at 05:32
-
BoxLayout works well for buttons, but not for JLabels...my JLabel is still aligned to the left. – Jimmt Jan 21 '12 at 23:40
-
The problem is that the JLabel extends all the way across the frame(determined by drawing a border). – Jimmt Jan 21 '12 at 23:46
-
Nevermind, I figured it out by setting the JLabel maximum size. Thanks for your answer. – Jimmt Jan 21 '12 at 23:54
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