添加包含JButton的Jpanel会干扰帧的结构

时间:2014-04-20 07:21:49

标签: java swing user-interface layout gridbaglayout

class Frame extends JFrame{

public Frame()
{
    JFrame jf= new JFrame("Student Admission");
    jf.setLayout(new GridLayout(5,1));
    JPanel jpn= new JPanel();


    JPanel enr= new JPanel();
    enr.setLayout(new FlowLayout(FlowLayout.LEFT));
    JLabel enrno= new JLabel("Enrollment Number",JLabel.LEFT);
    JTextField enrnoinput=new JTextField(3);
    enr.add(enrno);
    enr.add(enrnoinput);
    jf.add(enr);


    JLabel name= new JLabel("Student's Name",JLabel.LEFT);
    JTextField nameinput=new JTextField(60);
    jpn.add(name);
    jpn.add(nameinput);
    jf.add(jpn);

    JPanel jpfn= new JPanel();
    JLabel fname= new JLabel("Fathers's Name",JLabel.LEFT);
    JTextField fnameinput=new JTextField(60);
    jpfn.add(fname);
    jpfn.add(fnameinput);
    jf.add(jpfn);


    JPanel hscp= new JPanel();
    hscp.setLayout(new FlowLayout(FlowLayout.LEFT));
    JLabel hscper= new JLabel("Hsc Percentage",JLabel.LEFT);
    JTextField hscperinput=new JTextField(3);
    hscp.add(hscper);
    hscp.add(hscperinput);
    jf.add(hscp);


    JPanel sscp= new JPanel();
    sscp.setLayout(new FlowLayout(FlowLayout.LEFT));
    JLabel sscper= new JLabel("Ssc Percentage",JLabel.LEFT);
    JTextField sscperinput=new JTextField(3);
    sscp.add(sscper);
    sscp.add(sscperinput);
    jf.add(sscp);

    //After Adding this panel the frame's structure get disturbed
    JPanel buttonPanel= new JPanel();
    JButton save= new JButton("Save");
    JButton cancel= new JButton("Cancel");
    buttonPanel.add(save);
    buttonPanel.add(cancel);
    jf.add(buttonPanel);


    jf.setResizable(false);
    jf.pack();
    jf.setVisible(true);
    jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
} 

添加buttonPanel之前 enter image description here

添加buttonPanel enter image description here

我想在框架的中下部添加按钮面板,我该怎么做?

1 个答案:

答案 0 :(得分:2)

您的网格布局仅占5个组件,因此在您使用时会将所有内容搞砸6.将buttonPanel添加到sscp面板,然后添加sscp面板到整体框架。

JPanel sscp= new JPanel();
sscp.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel sscper= new JLabel("Ssc Percentage",JLabel.LEFT);
JTextField sscperinput=new JTextField(3);
sscp.add(sscper);
sscp.add(sscperinput);

JPanel buttonPanel= new JPanel();
JButton save= new JButton("Save");
JButton cancel= new JButton("Cancel");
buttonPanel.add(save);
buttonPanel.add(cancel);
//change here
sscp.add(buttonPanel);
jf.add(sscp);

GUI