Nicholas Mattiacci Nicholas Mattiacci - 3 months ago 7
Java Question

Trouble with java layouts

I used to have a jframe with 2 components in it, each of them taking half of the width and all of the height:
splitscreen1

I achieved this with a gridlayout with 2 columns and 1 row, which worked fine. Although now I'd like to add a third component beneath the one on the right:
enter image description here

Does anybody know how I could achieve this?

Answer

You can try nesting some JPanels, for example:

Have a main pane with a FlowLayout which will hold the left and right panes.

On the right pane have a BoxLayout or GridLayout to hold the top and bottom pane.

In the example code below which gives the following output

enter image description here

I added some border colors so you can see how it works, I added some labels because I'm too lazy to override the getPreferredSize() of each JPanel, but I think this will give you the idea on how to go on from here.

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

public class LayoutExample {
    private JFrame frame;
    private JPanel pane;
    private JPanel leftPane;
    private JPanel rightPane;
    private JPanel topPane;
    private JPanel bottomPane;
    public static void main (String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LayoutExample().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame("Layout Example");
        pane = new JPanel();
        leftPane = new JPanel();
        rightPane = new JPanel();
        topPane = new JPanel();
        bottomPane = new JPanel();

        pane.setLayout(new FlowLayout());
        rightPane.setLayout(new GridLayout(2, 1, 5, 5));
        leftPane.add(new JLabel("PaneLeft"));
        topPane.add(new JLabel("PaneTop"));
        bottomPane.add(new JLabel("PaneBottom"));


        rightPane.add(topPane);
        rightPane.add(bottomPane);

        pane.add(leftPane);
        pane.add(rightPane);
        pane.setBorder(BorderFactory.createLineBorder(Color.green));
        leftPane.setBorder(BorderFactory.createLineBorder(Color.red));
        rightPane.setBorder(BorderFactory.createLineBorder(Color.blue));
        topPane.setBorder(BorderFactory.createLineBorder(Color.cyan));
        bottomPane.setBorder(BorderFactory.createLineBorder(Color.pink));

        frame.setContentPane(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}