Patrick Reck
Patrick Reck

Reputation: 11374

BoxLayout sticking to top

I just started messing around with the BoxLayout manager.

I've made two buttons next to each other, and the third one should go to the next line (underneath the first two), and the two first buttons should be at the top of the frame.

How can I accomplish this?

This is my current code

    Box box = Box.createHorizontalBox();
    box.add(Box.createHorizontalGlue());
    box.add(new JButton("Button"));
    box.add(new JButton("Hello"));


    box.add(Box.createVerticalBox());
    box.add(Box.createVerticalStrut(100));
    box.add(new JButton("Button2"));

    add(box);

enter image description here

Upvotes: 0

Views: 138

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

Your current code looks nothing like the description you give of what you want. It sounds like you need

  • a top-level vertical box
    • a horizontal box
      • button
      • gap
      • button
    • gap
    • button

So something like

Box vbox = Box.createVerticalBox();

Box hbox = Box.createHorizontalBox();
hbox.add(new JButton("Button"));
hbox.add(Box.createHorizontalStrut(10));
hbox.add(new JButton("Hello"));
vbox.add(hbox);

vbox.add(Box.createVerticalStrut(100));
vbox.add(new JButton("Button2"));

Upvotes: 2

Related Questions