gpt4 book ai didi

java - 如果 setLayout 为 null,面板不显示任何内容

转载 作者:太空宇宙 更新时间:2023-11-04 13:42:42 25 4
gpt4 key购买 nike

我创建了一个 JPanel 并向其中添加了一个 JTabbedPane。然后我向该选项卡 Pane 添加了另外两个面板,并将所有面板的布局设置为 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());
}
}

主面板:

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 设置了绑定(bind)

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com