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

我的代码:
我正在为每个组件创建对象,并通过检查null约束在指定的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;
}

}

最佳答案

问题是这种方法

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);
}


如您所见,我们为子组件jtabbedpane设置了绑定

tab1.setBounds(0, 0, 650, 520);

关于java - 如果setLayout为null,则面板不显示任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31111541/

10-11 22:20
查看更多