Which Swing layout manager to get my desired layout?

A common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer.
This also applies to gui: break the design into small, easy to layout containers.
In this case, for example start by dividing the design into 3 areas:

enter image description here

Each such area is implemented by a nested panel.
As you can see in the code, mainPanel is further divided into two nested panels, to ease and improve layout:

class EcranAccueil extends JPanel {

    EcranAccueil(){
        //Set layout (JPanel uses Flowlayout by default)
        setLayout(new BorderLayout(5,5));

        // a nested panel for application label
        JPanel topPanel = new JPanel();
        add(topPanel, BorderLayout.NORTH);
        topPanel.setLayout(new FlowLayout(FlowLayout.LEADING));//set

        JLabel labelTitre=  new JLabel("ApplicationName");
        topPanel.add(labelTitre);

        // a nested panel for login and password, having two rows
        JPanel mainPanel = new JPanel(new GridLayout(2, 1));
        add(mainPanel, BorderLayout.CENTER);

        JPanel loginPanel = new JPanel();
        loginPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));
        mainPanel.add(loginPanel);

        JLabel labelLogin = new JLabel("Login");
        loginPanel.add(labelLogin);

        JTextField loginUser = new JTextField("User");
        loginUser.setColumns(10);
        loginPanel.add(loginUser);

        JPanel passwordPanel = new JPanel();
        passwordPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));
        mainPanel.add(passwordPanel);
        JLabel labelMotDepasse = new JLabel("Password");
        passwordPanel.add(labelMotDepasse);
        JTextField motDepasseUser = new JTextField("Password");
        motDepasseUser.setColumns(10);
        passwordPanel.add(motDepasseUser);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        add(buttonPanel,BorderLayout.SOUTH);
        JButton boutonConnexion = new JButton("Connect");
        buttonPanel.add(boutonConnexion);
    }
}

Once you get the basic idea, the layout and its responsiveness can be further improved.


More examples of applying this strategy: 1 2 and 3

Leave a Comment