2

I have created a GUI, and am using the FlowLayout.

I have 2 labels and a button, that are on the same line, however I want the button on a separate line to the 2 labels. Is there any way of going about it?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
David Horsley
  • 21
  • 2
  • 5

1 Answers1

4

There are many ways, most of which involve making a nested layout (putting one layout inside another). Here is an example.

Button/Label Layout

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

class ButtonLabelLayout {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JPanel gui = new JPanel(new BorderLayout());
                gui.setBorder(new TitledBorder("Border Layout"));

                JPanel labels = new JPanel();
                labels.setBorder(new TitledBorder("Flow Layout"));
                labels.add(new JLabel("Label 1"));
                labels.add(new JLabel("Label 2"));

                gui.add(labels, BorderLayout.NORTH);
                gui.add(new JButton("Button"), BorderLayout.SOUTH);

                JOptionPane.showMessageDialog(null, gui);
            }
        });
    }
}

For a more comprehensive example of nesting layouts, see this answer.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    the fan of nested panels :-) Can be done, but breaks down if cross-panel alignment is needed. Plus, fragments conceptually related "view" into bits dictated by implementation concerns. If there is a choice, don't - instead, group views by semantics and reach layout goals by _one_ decent LayoutManager – kleopatra Oct 23 '11 at 11:50
  • @kleopatra I considered using `GroupLayout` ( for an SSCCE, it's gotta' be J2SE ;), but that was more LOC. – Andrew Thompson Oct 23 '11 at 12:00
  • to consider GroupLayout you have to be tougher even than the GridBag bunch (So I was told, never wasted my time with any of advertized 'powerful' core managers, there are options out in the wild which give you all you need with considerably less effort) – kleopatra Oct 24 '11 at 07:49
  • @kleopatra I've used `GroupLayout` once or twice to good effect. It's worth having a look at (if you get bored with all your 3rd party layouts with chocolate sprinkles). – Andrew Thompson Oct 24 '11 at 08:26