How to move components to next line in FlowLayout?

Fawad Bin Tariq picture Fawad Bin Tariq · Dec 1, 2016 · Viewed 7.2k times · Source

I am adding components in JPanel which is set as FlowLayout, they are not moving on next line even there is no space in left in that line. Here is the screenshot of the problem

import javax.swing.*;
import java.awt.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
public class GUI extends JFrame
{
    private JLabel jlfname;
    private JPanel p1;
    private JTextField t1;
    private JLabel jllname;
    private JTextField t2;
    private JLabel jltitle;
    private JTextField t3;
    GUI()
    {
        jlfname=new JLabel("First Name : ");
        p1=new JPanel();
        TitledBorder titled = new TitledBorder("Name");
        p1.setBorder(titled);
        t1=new JTextField(10);
        jllname=new JLabel("Last Name : ");
        t2=new JTextField(10);
        jltitle=new JLabel("Title : ");
        t3=new JTextField(10);
        //Add in Pannel
        p1.setLayout(new FlowLayout());
        p1.add(jlfname);
        p1.add(t1);
        p1.add(jllname);
        p1.add(t2);
        p1.add(jltitle);
        p1.add(t3);
        //Add in Frame
        add(p1);
        setSize(550,500);
        setTitle("JFrame Tutorial");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setResizable(false);
        setVisible(true);
    }
    public static void main(String [] args)
    {
        new GUI();
    }
}

I have also tried to set width of the panel but it doesn't work!

Answer

camickr picture camickr · Dec 1, 2016

FlowLayout is designed to calculate its preferred size based on all components being displayed on a single line. The FlowLayout also respects the preferred size of components.

setLayout(new FlowLayout(FlowLayout.LEFT));

You are overriding the default layout manager of the frame, so now the frame will respect the preferred size of the panel added to the frame, which means all the components will be displayed on a single line.

Get rid of that statement.

Now the components will be able to wrap in the space available because by default the panel will be added to the BorderLayout.CENTER which takes up all the space available in the frame.

However the above solution will only work when components are added to the CENTER of the BorderLayout. Normally you should not be using setSize() but instead use pack() to all a frame to display at its preferred size.

For a more flexible layout that will calculate a proper preferred size of a panel check out the Wrap Layout. This class extends FlowLayout to calculate the preferred size.