如果setLayout为null,则Panel不显示任何内容

时间:2015-06-29 08:56:43

标签: java jpanel jtabbedpane

我创建了一个JPanel并为其添加了一个JTabbedPane。然后我在这个tabbedpane中添加了另外两个面板,并且我将setLayout设置为所有面板的null。但框架没有显示任何内容,如果我将布局从null更改为BorderLayout或GridLayout为主面板,那么它的工作完美。有人可以告诉我这里有什么问题..在此先感谢

我的代码: 我正在为每个组件创建对象,并通过检查空约束

在指定的getter中为它们设置边界

第一小组:

public class InsurancePanel extends JPanel
{
public InsurancePanel()
{
    getJpInsurance();
}

private static final long   serialVersionUID    = 1L;

public void getJpInsurance()
{
    setLayout(null);
    add(getJlLICName());
    add(getJlCompany());

    add(getJtfLICName());
    add(getJtfCompany());

    add(getJbUpdate());
}
}

第二小组:

public class PatientPanel extends JPanel
{

public PatientPanel()
{
    getJpPatient();
 }

private static final long   serialVersionUID    = 1L;

public void getJpPatient()
{
    setLayout(null);
    add(getJlFirstName());
    add(getJlLastName());

    add(getJtfFirstName());
    add(getJtfLastName());

    add(getJbNew());
}
}

MainPanel:

public class MainPanel extends JPanel
{
private PatientPanel        m_PatientPanel;
private InsurancePanel      m_InsurancePanel;
private JTabbedPane jtpView;

public void designMainPanel()
{
    setLayout(new GridLayout()); // if it is null, then nothing shows in the frame
    setSize(650, 520);
    setBounds(0, 0, 650, 520);
    add(getJtpView());
}

public JTabbedPane getJtpView()
{
    if (jtpView == null)
    {
        jtpView = new JTabbedPane();
        jtpView.addTab("Patient", getPatientPanel());
        jtpView.addTab("Insurance", getInsurancePanel());
    }
    return jtpView;
}

    public PatientPanel getPatientPanel()
{
    if (m_PatientPanel == null)
    {
        m_PatientPanel = new PatientPanel();
    }
    return m_PatientPanel;
}

public InsurancePanel getInsurancePanel()
{
    if (m_InsurancePanel == null)
    {
        m_InsurancePanel = new InsurancePanel();
    }
    return m_InsurancePanel;
}

}

1 个答案:

答案 0 :(得分:0)

问题在于此方法

public void designMainPanel()
{
    setLayout(null); // if it is null, then nothing shows in the frame
    setSize(650, 520);
    setBounds(0, 0, 650, 520); // ←---- problem is here
    add(getJtpView());
}

将子组件添加到父容器时,应指定子组件的x,y位置和宽度,高度。 在此代码中,您的父组件为MainPanel 并且您正在尝试添加getJtpView() JTabbedPane这是子组件。但是您将父组件的边界设置为不属于子组件(getJtpView() JTabbedPane)。

你应该把它改成

public void designMainPanel() {
    setLayout(null); //here it's null but it's working now
    JTabbedPane tab1 = getJtpView();
    tab1.setBounds(0, 0, 650, 520); //←---fixed:set bound to child JTabbedPane 
    add(tab1);
}

你可以看到我们为child component-jtabbedpane

设置了绑定
tab1.setBounds(0, 0, 650, 520);