JFrame是最底层,JPanel是置于其面上,同一个界面只有一个JFrame,一个JFrame可以放多个JPanel。如果你直接在JFrame上放也可以,但是首先不规范,然后要是过于复杂的界面你准备如何处理这么多控件呢?
对于java页面的布局,我的理解就是JFrame 就像是一张大的桌子,你可以直接把鱼呀,肉了,直接放在桌面上,没有盘子进行分类管理,这时我们就需要jpanel这样的盘子来放我们需要的一些控件。便于管理。
下面我们来看看示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Mystudent extends WindowAdapter implements ActionListener,ItemListener //定义事件处理类,由它对按钮和框架上的窗口产生的事件进行处理 { Frame f; //框架对象 Button b1,b2; TextField name2,id2,number2,email2; Label name1,sex,id1,number1,email1; List l; JComboBox cb; public Mystudent() //构造窗口界面 { f = new Frame("学生信息输入窗口"); //创建带标题的框架 f.setSize(600,300); //设置框架大小 l=new List(); //l.add("姓名 学号 电话 邮箱 性别 "); f.add(l); Panel p = new Panel(); p.setLayout(new GridLayout(6, 2));//将以上图片的右半部分分成6行2列。 f.add(p,"East"); name1=new Label("姓名"); name2 = new TextField(10); id1=new Label("学号"); id2 = new TextField(10); number1=new Label("电话"); number2 = new TextField(10); email1= new Label("邮箱"); email2 = new TextField(10); sex=new Label("性别"); String[] a={"男","女"}; cb=new JComboBox (a); b1 = new Button("增加"); //创建按钮对象 b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { // if(name.getText().trim().length()==0||new String(password.getPassword()).trim().length()==0){ // JOptionPane.showMessageDialog(null, "用户名密码不允许为空"); // return; // } boolean key; key=number2.getText().trim().matches("^[1]\\d{10}$")&&email2.getText().trim().matches("\\w+@\\w+\\.\\w{2,3}"); if(key){ JOptionPane.showMessageDialog(null, "输入学生信息正确"); } else{ JOptionPane.showMessageDialog(null, "学生邮箱或手机号有误,请重新输入"); } } }); b2= new Button("删除"); p.add(name1); p.add(name2); p.add(id1); p.add(id2); p.add(number1); p.add(number2); p.add(email1); p.add(email2); p.add(sex); p.add(cb); p.add(b1); //在框架中加入按钮 p.add(b2); b1.addActionListener(this); //注册,按钮的单击事件由对象自己处理 b2.addActionListener( this); cb.addActionListener(this); l.addItemListener(this); f.setVisible(true); //设置框架为可见 f.addWindowListener(this); //注册监听框架上的窗口事件 } public void actionPerformed(ActionEvent e) //处理按钮单击事件 { boolean key; key=number2.getText().trim().matches("^[1]\\d{10}$")&&email2.getText().trim().matches("\\w+@\\w+\\.\\w{2,3}"); if(e.getSource()==b1&&key){ l.add("姓名: "+name2.getText()+" "+"学号: "+id2.getText()+" "+"电话: "+number2.getText()+" "+"邮箱: "+email2.getText()+" "+"性别: "+cb.getSelectedItem()); } if(e.getSource()==b2){ l.remove(l.getSelectedIndex()); } } public void windowClosing(WindowEvent e)// 处理窗口关闭事件 { System.exit(0); //程序停止运行,关闭框架窗口 } public void itemStateChanged(ItemEvent arg0) { // TODO Auto-generated method stub String str=l.getSelectedItem(); int i = str.indexOf(' '); //获得串中第一个空格的位置 name2.setText(str.substring(0,i)); //设置文本行显示内容 str = str.substring(i); //取从i位置开始的子串 str = str.trim(); } public static void main(String args[]) { Mystudent stu= new Mystudent(); } }