David Horsley
David Horsley

Reputation: 21

GUI - getting something on next line

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?

Upvotes: 2

Views: 3523

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

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.

Upvotes: 4

Related Questions