javaswinggrid-layoutgridlayoutmanagernestedlayout

Java nested layouts


Hy, I'm trying to create a window with a layout like in this picture:

layout

My ide was to use panels and nest layouts something like that:

layout2

Here is my code so far, but it is not working properly. How should I do that, what should I do differently, or even my basic concept is wrong?

package layout;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
import models.People;

public class DetailWindow extends JFrame{

public DetailWindow(People newPeople) {
    JFrame frame = new JFrame("Detail Window");
    
    JPanel mainPanel = new JPanel(new GridLayout(1,2));
    frame.add(mainPanel);

    JPanel leftPanel = new JPanel(new GridLayout(2,1));
    frame.add(leftPanel);
    
    JPanel rightPanel = new JPanel(new GridLayout(3,1));
    frame.add(rightPanel);
    
    JPanel pictureHolder = new JPanel(new FlowLayout());
    pictureHolder.add(new JLabel(new ImageIcon(newPeople.getPic())));
    leftPanel.add(pictureHolder);
    
    JPanel infoHolder = new JPanel(new GridLayout(6,1));
    infoHolder.add(new JTextField(newPeople.getLb_name()));
    infoHolder.add(new JTextField(newPeople.getName()));
    infoHolder.add(new JTextField(newPeople.getLb_occup()));
    infoHolder.add(new JTextField(newPeople.getOccup()));
    infoHolder.add(new JTextField(newPeople.getLb_BD()));
    infoHolder.add(new JTextField(newPeople.getBD()));
    leftPanel.add(infoHolder);

    
    rightPanel.add(new JTextField(newPeople.getName()));
    rightPanel.add(new JTextField(newPeople.getOccup()));
    rightPanel.add(new JTextField(newPeople.getDetail()));
    
    frame.pack();
    frame.setSize(600, 400);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.show();
  }
}

(The People is a custom class, and in the main I just call the DetailWindow constructor)

Thanks for the help in advance!


Solution

  • By looking at your pictures, I would use the GridBagLayout as explained here.

    The reason for this is that GridBagLayout is the easiest layout when working with multiple panels, it works on the same basis as a basic matrix to position your UI elements, to space them perfectly you can just use a spacer, i.e. an empty layout with a fixed size between the panels.

    On the other hand, there are lots of brilliant ide`s out there, I prefer IntelliJ idea, which has a super UI 'generator' and allows you to space your UI exactly the way you want.

    Good luck :)