Faw*_*riq 6 java swing layout-manager flowlayout
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();
}
}
Run Code Online (Sandbox Code Playgroud)
I have also tried to set width of the panel but it doesn't work!
FlowLayout 旨在根据单行上显示的所有组件计算其首选大小。FlowLayout 还尊重组件的首选大小。
setLayout(new FlowLayout(FlowLayout.LEFT));
Run Code Online (Sandbox Code Playgroud)
您将覆盖框架的默认布局管理器,因此现在框架将遵循添加到框架的面板的首选大小,这意味着所有组件将显示在一行上。
摆脱该声明。
现在,组件将能够在可用空间中换行,因为默认情况下,面板将添加到 BorderLayout.CENTER,它占用了框架中的所有可用空间。
然而,上述解决方案仅在将组件添加到 BorderLayout 的中心时才有效。通常你不应该使用 setSize() 而是使用 pack() 来让所有框架以其首选大小显示。
要获得更灵活的布局来计算面板的正确首选尺寸,请查看Wrap Layout。此类扩展 FlowLayout 以计算首选大小。