第三:主界面实现代码:
package com.sc.test3;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
* 学生管理的主界面
* @author ZhangShaoWen
*
*/
public class StuManage extends JFrame implements ActionListener{
//定义控件
JLabel jl1;
JTextField jtf1;
JButton jb1,jb2,jb3,jb4;
JScrollPane jsp;
JTable jt;
JPanel jp1,jp2;
StuModel sm;
public static void main(String[] args) {
StuManage s = new StuManage();
}
//构造函数
public StuManage(){
//构建第一个jpanel
jp1 = new JPanel();
jl1 = new JLabel("请输入名字");
jtf1 = new JTextField(10);
jb1 = new JButton("查询");
jb1.addActionListener(this);//注册监听
//把控件加入到jp1
jp1.add(jl1);
jp1.add(jtf1);
jp1.add(jb1);
//构建第二个JPanel
jp2 = new JPanel();
jb2 = new JButton("添加");
jb2.addActionListener(this);//添加按钮注册监听
jb3 = new JButton("修改");
jb3.addActionListener(this);//修改按钮注册监听
jb4 = new JButton("删除");
jb4.addActionListener(this);//删除按钮注册监听
//把控件加入到jp2
jp2.add(jb2);
jp2.add(jb3);
jp2.add(jb4);
//创建一个数据库模型对象
sm = new StuModel();
String paras[] = {"1"};
sm.queryStu("select * from stu where 1=?", paras);
//初始化jt
jt = new JTable(sm);
//初始化jsp
jsp = new JScrollPane(jt);
this.add(jsp);
this.add(jp1,"North");
this.add(jp2,"South");
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
//监听器
@Override
public void actionPerformed(ActionEvent e) {
//判断点击的按钮
//当点击查询按钮时
if(e.getSource()==jb1){
String name = jtf1.getText();
String sql = "select * from stu where stuName=?";
String paras[] = {name};
sm = new StuModel();
sm.queryStu(sql, paras);
//
jt.setModel(sm);
}
//当点击添加按钮时
if(e.getSource()==jb2){
StuAddDialog stua = new StuAddDialog(this,"添加学生",true);
//创建新的数据模型,并更新
sm = new StuModel();
String[] paras = {"1"};
sm.queryStu("select * from stu where 1=?", paras);
//更新JTable
jt.setModel(sm);
}
//当点击修改按钮时
if(e.getSource()==jb3){
StuModel temp = new StuModel();
sm = new StuModel();
//得到行号
int rowNums = this.jt.getSelectedRow();
if(rowNums==-1){
JOptionPane.showMessageDialog(this,"请选择一行");
}
new StuUpDialog(this,"修改信息",true,sm,rowNums);
String []paras = {"1"};
sm.queryStu("select * from stu where 1=?", paras);
jt.setModel(sm);
}
//当点击删除按钮时
if(e.getSource()==jb4){
//得到行号
int rowNums = this.jt.getSelectedRow();
if(rowNums==-1){
JOptionPane.showMessageDialog(this,"请选择一行");
return ;
}
//得到学生的学号
String stuNo = (String)sm.getValueAt(rowNums, 0);
String paras[]={stuNo,"1"};
StuModel temp = new StuModel();
temp.updStu("delete from stu where stuId=? and 1=?", paras);
//创建新的数据模型
sm = new StuModel();
String[] paras2={"1"};
sm.queryStu("select * from stu where 1=?", paras2);
//更新JTable
jt.setModel(sm);
}
}
}