在另一个内部有多个JPanel

时间:2016-02-22 17:29:18

标签: java jpanel

look here 我必须制作这样的格式,比如制作一个1,2面板,然后在左侧放一个3,1面板。然后,我在左中左侧面板中放置了4个文本字段,在左下方面板中放置了一个按钮。

我不确定我是否可以使用GridLayout,或者我是否也必须使用BorderLayout。

我怎样才能把这个组织起来,因为当我设置它时,我无法正确地进行布局。文本字段不在正确的位置,它们最终位于右侧。

public class CreatePanel extends JPanel
 {
   private Vector projectList;
   private JButton button1;
   private ProjectSpendingPanel spendingPanel;

   private JFrame frame1;
   JPanel panel1;
   JPanel leftPanel;
   JPanel subPanel;

   GridLayout layout1;
   BorderLayout layout2;
   GridLayout layout3;

   JLabel message;
   JLabel labelName;
   JLabel labelNumber;
   JLabel labelLocation;
   JLabel labelFunding;

   JTextField textField1;
   JTextField textField2;
   JTextField textField3;
   JTextField textField4;

 //Constructor initializes components and organize them using certain layouts
 public CreatePanel(Vector projectList, ProjectSpendingPanel spendingPanel)
  {
    this.projectList = projectList;
    this.spendingPanel = spendingPanel;
	//organize components here
	layout1 = new GridLayout(1,2);
	layout2 = new BorderLayout(1,3);
	layout3 = new GridLayout(4,2);
	this.setLayout(layout1);

	panel1 = new JPanel(layout1);
	leftPanel = new JPanel(layout3);
	subPanel = new JPanel(layout2);

	add(panel1);
	panel1.add(subPanel);
	panel1.add(leftPanel);

	labelName = new JLabel("Project Name");
	leftPanel.add(labelName);
	textField1 = new JTextField("", 15);
    leftPanel.add(textField1,BorderLayout.SOUTH);

	labelName = new JLabel("Project Number");
	leftPanel.add(labelName);
	textField2 = new JTextField("",15);
	leftPanel.add(textField2);

	labelLocation = new JLabel("Project Location");
	leftPanel.add(labelLocation);
	textField3 = new JTextField("",15);
	leftPanel.add(textField3);

	labelFunding = new JLabel("Initial Funding");
	leftPanel.add(labelFunding);
	textField4 = new JTextField("",15);
	leftPanel.add(textField4);

	add(leftPanel);
    button1 = new JButton("Create a project");
    subPanel.add(button1,BorderLayout.SOUTH);
  }

1 个答案:

答案 0 :(得分:0)

要获得您可能想要的结果,您需要稍微调整一下代码。

你的行

panel1 = new JPanel(layout1);
leftPanel = new JPanel(layout3);
subPanel = new JPanel(layout2);

应改为阅读

panel1 = new JPanel(new GridLayout(2, 1));
leftPanel = new JPanel(layout3);
subPanel = new JPanel(layout2);

GridLayout首先获取行,然后是列。您的layout1定义了一行和两列,但您将其用于文本字段和按钮,因此我假设这两个面板需要在彼此之上。

其次,您需要更改

的顺序
add(panel1);
panel1.add(subPanel);
panel1.add(leftPanel);

add(panel1);
panel1.add(leftPanel);
panel1.add(subPanel);

最后,我认为你需要改变

add(leftPanel);
button1 = new JButton("Create a project");

add(spendingPanel);
button1 = new JButton("Create a project");

再次添加leftPanel似乎会破坏布局。如果您不想在此处看到spendingPanel,则可以改为使用new JPanel()

这是screenshot of the running program