写了蛮久的综合课设大作业,今天分享一下下,我们需要创建的是一个maven项目,该作业使用到了 Java + MySQL + GUI 实现,具体可见下面。
一、展示:
登陆界面:
主界面:
添加界面:
修改界面:
二、目录:
创建的maven项目初始样子:
创建好包、类之后:
三、代码:
Tourist:
packageClass;//游客类publicclassTourist{String id;String name;String age;String gender;String sort;String inTime;String outTime;publicTourist(String id,String name,String age,String gender,String sort,String inTime,String outTime){this.id = id;this.name = name;this.age = age;this.gender = gender;this.sort = sort;this.inTime = inTime;this.outTime = outTime;}publicTourist(String name,String age,String gender,String sort,String inTime,String outTime){this.id = id;this.name = name;this.age = age;this.gender = gender;this.sort = sort;this.inTime = inTime;this.outTime = outTime;}publicStringgetId(){return id;}publicStringgetName(){return name;}publicStringgetAge(){return age;}publicStringgetGender(){return gender;}publicStringgetSort(){return sort;}publicStringgetInTime(){return inTime;}publicStringgetOutTime(){return outTime;}}
AddView :
packageJFrame;//添加界面importOperate.TouristOperate;importjavax.swing.*;importjava.awt.*;publicclassAddViewextendsJDialog{JPanel jPanel =newJPanel(newFlowLayout(FlowLayout.CENTER,10,20));//水平间距垂直间距调节JLabel nameLab =newJLabel("姓名:",JLabel.RIGHT);//右对齐JTextField nameTxt =newJTextField();JLabel ageLab =newJLabel("年龄:",JLabel.RIGHT);JTextField ageTxt =newJTextField();JLabel genderLab =newJLabel("性别:",JLabel.RIGHT);// 创建下拉框JComboBox comboBox1 =newJComboBox();JLabel sortLab =newJLabel("人群类型:",JLabel.RIGHT);// 创建下拉框JComboBox comboBox2 =newJComboBox();// 绑定下拉框选项String[]Array={"少年","青年","中年","老年"};JLabel inLab =newJLabel("入园时间:",JLabel.RIGHT);JTextField inTxt =newJTextField();JLabel outLab =newJLabel("离园时间:",JLabel.RIGHT);JTextField outTxt =newJTextField();JButton addBt =newJButton("添加");//游客操作按钮监听TouristOperate touristOperate;publicAddView(MainView mainView){//该窗体以来mainViewsuper(mainView,"信息添加",true);
touristOperate =newTouristOperate(this);
nameLab.setPreferredSize(newDimension(80,30));
jPanel.add(nameLab);
nameTxt.setPreferredSize(newDimension(200,30));
jPanel.add(nameTxt);
ageLab.setPreferredSize(newDimension(80,30));
jPanel.add(ageLab);
ageTxt.setPreferredSize(newDimension(200,30));
jPanel.add(ageTxt);
genderLab.setPreferredSize(newDimension(80,30));
jPanel.add(genderLab);
comboBox1.addItem("男");
comboBox1.addItem("女");
jPanel.add(comboBox1);//选项框
sortLab.setPreferredSize(newDimension(80,30));
jPanel.add(sortLab);for(String s :Array){
comboBox2.addItem(s);}
jPanel.add(comboBox2);
inLab.setPreferredSize(newDimension(80,30));
jPanel.add(inLab);
inTxt.setPreferredSize(newDimension(200,30));
jPanel.add(inTxt);
outLab.setPreferredSize(newDimension(80,30));
jPanel.add(outLab);
outTxt.setPreferredSize(newDimension(200,30));
jPanel.add(outTxt);
jPanel.add(addBt);
addBt.addActionListener(touristOperate);//加入面板Container contentPane =getContentPane();
contentPane.add(jPanel);//常规设置 !!!:放最后 小心吃亏setSize(350,370);//设置大小setLocationRelativeTo(null);//居中setDefaultCloseOperation(DISPOSE_ON_CLOSE);//点击关闭 不销毁整个程序 DISPOSE_ON_CLOSE只关闭当前窗体setResizable(false);//大小不可变setVisible(true);//可视化}publicJTextFieldgetNameTxt(){return nameTxt;}publicJTextFieldgetAgeTxt(){return ageTxt;}publicJComboBoxgetComboBox1(){return comboBox1;}publicJComboBoxgetComboBox2(){return comboBox2;}publicJTextFieldgetInTxt(){return inTxt;}publicJTextFieldgetOutTxt(){return outTxt;}}
J_Table :
packageJFrame;//表格importjavax.swing.*;importjavax.swing.table.DefaultTableCellRenderer;importjavax.swing.table.JTableHeader;importjava.awt.*;publicclassJ_TableextendsJTable{publicJ_Table(){//设置表头JTableHeader tableHeader =getTableHeader();
tableHeader.setFont(newFont(null,Font.BOLD,22));//字形 粗细 大小
tableHeader.setForeground(Color.RED);//字体颜色//设置表格体setFont(newFont(null,Font.PLAIN,18));setRowHeight(25);//设置表格行高setForeground(Color.black);setGridColor(Color.BLACK);//线条//设置多行选择getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//表格字体居中DefaultTableCellRenderer r=newDefaultTableCellRenderer();
r.setHorizontalAlignment(JLabel.CENTER);setDefaultRenderer(Object.class,r);}}
**LoginView:登录面板里面右上角有一个小图标,是通过
URL url = LoginView.class.getClassLoader().getResource("qq.jpg")
实现的,图片我没给,可以选择自己喜欢的一张拖进resources 包下,然后更改对应路径名就可以了。**
packageJFrame;//登陆界面importOperate.LoginOperate;importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importjava.net.URL;publicclassLoginViewextendsJFrame{JLabel nameLab =newJLabel("Java -皇家公园管理系统",JLabel.CENTER);SpringLayout springLayout =newSpringLayout();//弹簧布局//中心面板JPanel centerPanel =newJPanel(springLayout);//用户名JLabel userNameLab =newJLabel("用户名:");JTextField userTxt =newJTextField();//密码JLabel passWordLab =newJLabel("密码:");JPasswordField passWordTxt =newJPasswordField();//按钮JButton loginBt =newJButton("登录");JButton resetBt =newJButton("重置");//增加系统托盘TrayIcon trayIcon;SystemTray systemTray;//按钮事件处理LoginOperate loginHandler;//初始化publicLoginView(){super("公园管理系统登录");Container contentPane =getContentPane();//new对象才能操作this.loginHandler =newLoginOperate(this);//设置字体大小等
nameLab.setFont(newFont("华文行楷",Font.PLAIN,40));
nameLab.setPreferredSize(newDimension(0,120));Font centerFont =newFont("楷体",Font.PLAIN,20);
userNameLab.setFont(centerFont);
userTxt.setPreferredSize(newDimension(200,30));//设置大小
passWordLab.setFont(centerFont);
passWordTxt.setPreferredSize(newDimension(200,30));
loginBt.setFont(centerFont);
resetBt.setFont(centerFont);//加入面板
centerPanel.add(userNameLab);
centerPanel.add(userTxt);
centerPanel.add(passWordLab);
centerPanel.add(passWordTxt);
centerPanel.add(loginBt);
centerPanel.add(resetBt);//按钮事件处理
loginBt.addActionListener(loginHandler);
resetBt.addActionListener(loginHandler);//弹簧布局//布局userNameLabSpring childWidth =Spring.sum(Spring.sum(Spring.width(userNameLab),Spring.width(userTxt)),Spring.constant(20));int offsetX = childWidth.getValue()/2;
springLayout.putConstraint(SpringLayout.WEST, userNameLab,-offsetX,SpringLayout.HORIZONTAL_CENTER, centerPanel);
springLayout.putConstraint(SpringLayout.NORTH, userNameLab,20,SpringLayout.NORTH, centerPanel);//userTxt
springLayout.putConstraint(SpringLayout.WEST, userTxt,20,SpringLayout.EAST, userNameLab);
springLayout.putConstraint(SpringLayout.NORTH, userTxt,0,SpringLayout.NORTH, userNameLab);//passWordLab
springLayout.putConstraint(SpringLayout.EAST, passWordLab,0,SpringLayout.EAST, userNameLab);
springLayout.putConstraint(SpringLayout.NORTH, passWordLab,20,SpringLayout.SOUTH, userNameLab);//passWordTxt
springLayout.putConstraint(SpringLayout.WEST, passWordTxt,20,SpringLayout.EAST, passWordLab);
springLayout.putConstraint(SpringLayout.NORTH, passWordTxt,0,SpringLayout.NORTH, passWordLab);//按钮loginBt
springLayout.putConstraint(SpringLayout.WEST, loginBt,20,SpringLayout.WEST, passWordLab);
springLayout.putConstraint(SpringLayout.NORTH, loginBt,40,SpringLayout.SOUTH, passWordLab);//按钮resetBt
springLayout.putConstraint(SpringLayout.WEST, resetBt,80,SpringLayout.EAST, loginBt);
springLayout.putConstraint(SpringLayout.NORTH, resetBt,0,SpringLayout.NORTH, loginBt);//放入内容面板
contentPane.add(nameLab,BorderLayout.NORTH);
contentPane.add(centerPanel,BorderLayout.CENTER);//实现最小化到托盘URL url =LoginView.class.getClassLoader().getResource("qq.jpg");if(SystemTray.isSupported()){
systemTray =SystemTray.getSystemTray();
trayIcon =newTrayIcon(newImageIcon(url).getImage());
trayIcon.setImageAutoSize(true);try{
systemTray.add(trayIcon);}catch(AWTException e){
e.printStackTrace();}//最小化时销毁窗口this.addWindowListener(newWindowAdapter(){@OverridepublicvoidwindowIconified(WindowEvent e){LoginView.this.dispose();}});//托盘事件监听
trayIcon.addMouseListener(newMouseAdapter(){@OverridepublicvoidmouseClicked(MouseEvent e){int clickCount = e.getClickCount();if(clickCount ==1){LoginView.this.setExtendedState(JFrame.NORMAL);}LoginView.this.setVisible(true);//可视化}});}//常规设置 !!!:放最后 小心吃亏setIconImage(newImageIcon(url).getImage());setSize(600,400);//设置大小setLocationRelativeTo(null);//居中setDefaultCloseOperation(EXIT_ON_CLOSE);//点击关闭关闭程序setResizable(false);//大小不可变setVisible(true);//可视化}publicJTextFieldgetUserTxt(){return userTxt;}publicvoidsetUserTxt(JTextField userTxt){this.userTxt = userTxt;}publicJPasswordFieldgetPassWordTxt(){return passWordTxt;}publicvoidsetPassWordTxt(JPasswordField passWordTxt){this.passWordTxt = passWordTxt;}}
MainView :
packageJFrame;//主界面importOperate.TouristOperate;importjavax.swing.*;importjava.awt.*;importjava.net.URL;importjava.util.Vector;publicclassMainViewextendsJFrame{JPanel northPanel =newJPanel(newFlowLayout(FlowLayout.LEFT));JButton addBt =newJButton("增加");JButton updateBt =newJButton("修改");JButton delBt =newJButton("删除");JTextField searchTxt1 =newJTextField(10);JLabel line =newJLabel("—");JTextField searchTxt2 =newJTextField(10);JButton searchBT =newJButton("时间查询");JButton searchName =newJButton("姓名查询");// JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));// JButton preBt = new JButton("上一页");// JButton nextBt = new JButton("下一页");J_Table table =newJ_Table();//游客操作按钮监听TouristOperate touristOperate;publicMainView(){super("公园管理系统");Container contentPane =getContentPane();//new对象了才能进行操作this.touristOperate =newTouristOperate(this);//上方按钮layoutNorth(contentPane);//中间表格题layoutCenter(contentPane);// //下方按钮// layoutSouth(contentPane);//常规设置 !!!:放最后 小心吃亏URL url =LoginView.class.getClassLoader().getResource("qq.jpg");setIconImage(newImageIcon(url).getImage());setSize(1300,800);//设置大小setLocationRelativeTo(null);//居中setDefaultCloseOperation(EXIT_ON_CLOSE);//点击关闭关闭程序setResizable(false);//大小不可变setVisible(true);//可视化}privatevoidlayoutCenter(Container contentPane){Vector<Vector<Object>> data =TouristOperate.getAllData();//更新table数据TableModel.updateModel(data);TableModel tableModel =TableModel.assembleModel(data);
table.setModel(tableModel);JScrollPane jScrollPane =newJScrollPane(table);
contentPane.add(jScrollPane,BorderLayout.CENTER);}// private void layoutSouth(Container contentPane) {// southPanel.add(preBt);// southPanel.add(nextBt);// contentPane.add(southPanel, BorderLayout.SOUTH);// }privatevoidlayoutNorth(Container contentPane){//增加事件监听
addBt.addActionListener(touristOperate);
updateBt.addActionListener(touristOperate);
delBt.addActionListener(touristOperate);
searchBT.addActionListener(touristOperate);
searchName.addActionListener(touristOperate);
northPanel.add(addBt);
northPanel.add(updateBt);
northPanel.add(delBt);
northPanel.add(searchTxt1);
northPanel.add(line);
northPanel.add(searchTxt2);
searchTxt1.setPreferredSize(newDimension(200,30));
searchTxt2.setPreferredSize(newDimension(200,30));
northPanel.add(searchBT);
northPanel.add(searchName);
contentPane.add(northPanel,BorderLayout.NORTH);}publicJTextFieldgetSearchTxt1(){return searchTxt1;}publicJTextFieldgetSearchTxt2(){return searchTxt2;}//获取选中的行的id用来进行修改和删除publicint[]getIds(){int[] selectedRows = table.getSelectedRows();int[] idx =newint[selectedRows.length];for(int i =0; i < selectedRows.length; i++){Object id = table.getValueAt(selectedRows[i],0);
idx[i]=Integer.parseInt(id.toString());}return idx;}}
TableModel :
packageJFrame;//table 模型importjavax.swing.table.DefaultTableModel;importjava.util.Vector;publicclassTableModelextendsDefaultTableModel{staticVector<String> cloumns =newVector<>();privatestaticTableModel tableModel =newTableModel();static{
cloumns.addElement("编号");
cloumns.addElement("姓名");
cloumns.addElement("年龄");
cloumns.addElement("性别");
cloumns.addElement("人群类型");
cloumns.addElement("入园时间");
cloumns.addElement("离园时间");}publicTableModel(){super(null, cloumns);}publicstaticTableModelassembleModel(Vector<Vector<Object>> data){
tableModel.setDataVector(data, cloumns);
tableModel.getColumnClass(200);return tableModel;}//更新数据表数据publicstaticvoidupdateModel(Vector<Vector<Object>> data){
tableModel.setDataVector(data, cloumns);}publicstaticVector<String>getCloumns(){return cloumns;}@OverridepublicbooleanisCellEditable(int row,int column){returnfalse;}}
UpdateView :
packageJFrame;//更新界面importOperate.TouristOperate;importUtil.DBUtil;importClass.*;importjavax.swing.*;importjava.awt.*;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;publicclassUpdateViewextendsJDialog{JPanel jPanel =newJPanel(newFlowLayout(FlowLayout.CENTER,10,20));//水平间距垂直间距调节JLabel idLab =newJLabel("编号:",JLabel.RIGHT);JTextField idTxt =newJTextField();JLabel nameLab =newJLabel("姓名:",JLabel.RIGHT);//右对齐JTextField nameTxt =newJTextField();JLabel ageLab =newJLabel("年龄:",JLabel.RIGHT);JTextField ageTxt =newJTextField();JLabel genderLab =newJLabel("性别:",JLabel.RIGHT);// 创建下拉框JComboBox comboBox1 =newJComboBox();JLabel sortLab =newJLabel("人群类型:",JLabel.RIGHT);// 创建下拉框JComboBox comboBox2 =newJComboBox();// 绑定下拉框选项String[]Array={"少年","青年","中年","老年"};JLabel inLab =newJLabel("入园时间:",JLabel.RIGHT);JTextField inTxt =newJTextField();JLabel outLab =newJLabel("离园时间:",JLabel.RIGHT);JTextField outTxt =newJTextField();JButton addBt =newJButton("确认修改");//游客操作按钮监听TouristOperate touristOperate;int id =-1;publicUpdateView(MainView mainView,int id){//该窗体以来mainViewsuper(mainView,"信息修改",true);
touristOperate =newTouristOperate(this);this.id = id;Tourist t =searchId(id);
idLab.setPreferredSize(newDimension(80,30));
jPanel.add(idLab);
idTxt.setPreferredSize(newDimension(200,30));
idTxt.setText(t.getId());
idTxt.setEditable(false);//设置文本域不能编辑 该处为主键 不可修改
jPanel.add(idTxt);
nameLab.setPreferredSize(newDimension(80,30));
jPanel.add(nameLab);
nameTxt.setPreferredSize(newDimension(200,30));
nameTxt.setText(t.getName());
jPanel.add(nameTxt);
ageLab.setPreferredSize(newDimension(80,30));
jPanel.add(ageLab);
ageTxt.setPreferredSize(newDimension(200,30));
ageTxt.setText(t.getAge());
jPanel.add(ageTxt);
genderLab.setPreferredSize(newDimension(80,30));
jPanel.add(genderLab);
comboBox1.addItem("男");
comboBox1.addItem("女");
comboBox1.setSelectedItem(t.getGender());
jPanel.add(comboBox1);//选项框
sortLab.setPreferredSize(newDimension(80,30));
jPanel.add(sortLab);for(String s :Array){
comboBox2.addItem(s);}
comboBox2.setSelectedItem(t.getSort());
jPanel.add(comboBox2);
inLab.setPreferredSize(newDimension(80,30));
jPanel.add(inLab);
inTxt.setPreferredSize(newDimension(200,30));
inTxt.setText(t.getInTime());
jPanel.add(inTxt);
outLab.setPreferredSize(newDimension(80,30));
jPanel.add(outLab);
outTxt.setPreferredSize(newDimension(200,30));
outTxt.setText(t.getOutTime());
jPanel.add(outTxt);
jPanel.add(addBt);
addBt.addActionListener(touristOperate);//加入面板Container contentPane =getContentPane();
contentPane.add(jPanel);//常规设置 !!!:放最后 小心吃亏setSize(350,400);//设置大小setLocationRelativeTo(null);//居中setDefaultCloseOperation(DISPOSE_ON_CLOSE);//点击关闭 不销毁整个程序 DISPOSE_ON_CLOSE只关闭当前窗体setResizable(false);//大小不可变setVisible(true);//可视化}//id查询privateTouristsearchId(int id){String sql ="select * from tourist where id = ?";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){returnnull;}
ps = con.prepareStatement(sql);
ps.setString(1,String.valueOf(id));
rs = ps.executeQuery();while(rs.next()){Tourist t =newTourist(rs.getString("id"),
rs.getString("name"),
rs.getString("age"),
rs.getString("gender"),
rs.getString("sort"),
rs.getString("in_time"),
rs.getString("out_time"));return t;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}returnnull;}publicJTextFieldgetIdTxt(){return idTxt;}publicJTextFieldgetNameTxt(){return nameTxt;}publicJTextFieldgetAgeTxt(){return ageTxt;}publicJComboBoxgetComboBox1(){return comboBox1;}publicJComboBoxgetComboBox2(){return comboBox2;}publicJTextFieldgetInTxt(){return inTxt;}publicJTextFieldgetOutTxt(){return outTxt;}}
AdminOp:
packageOperate;//管理员信息importUtil.DBUtil;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;publicclassAdminOp{publicstaticbooleanisLegal(String userName,String passWord){String sql ="select admin,pwd from manager";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){returnfalse;}
ps = con.prepareStatement(sql);
rs = ps.executeQuery();while(rs.next()){String user = rs.getString("admin");String pwd = rs.getString("pwd");if(userName.equals(user)&& passWord.equals(pwd)){returntrue;}}}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}returnfalse;}}
LoginOperate :
packageOperate;//登录操作importJFrame.LoginView;importJFrame.MainView;importjavax.swing.*;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;publicclassLoginOperateimplementsActionListener{publicLoginView loginView;publicLoginOperate(LoginView loginView){this.loginView = loginView;}@OverridepublicvoidactionPerformed(ActionEvent e){JButtonJBT=(JButton) e.getSource();String text =JBT.getText();if("登录".equals(text)){login();}elseif("重置".equals(text)){
loginView.getUserTxt().setText("");
loginView.getPassWordTxt().setText("");}}privatevoidlogin(){String user = loginView.getUserTxt().getText();String passWord =newString(loginView.getPassWordTxt().getPassword());//查询数据库是否有该用户boolean flag =AdminOp.isLegal(user, passWord);if(flag){//跳转主界面 and 销魂登录界面newMainView();
loginView.dispose();}else{//报错窗口JOptionPane.showMessageDialog(loginView,"用户名密码错误!!!");}}}
TouristOperate:
packageOperate;//游客操作importUtil.DBUtil;importJFrame.*;importClass.*;importjavax.swing.*;importjava.awt.event.*;importjava.sql.*;importjava.util.Vector;publicclassTouristOperateimplementsActionListener{publicMainView mainView;publicAddView addView;publicUpdateView updateView;publicTouristOperate(MainView mainView){this.mainView = mainView;}publicTouristOperate(AddView addView){this.addView = addView;}publicTouristOperate(UpdateView updateView){this.updateView = updateView;}@OverridepublicvoidactionPerformed(ActionEvent e){JButtonJBT=(JButton) e.getSource();String text =JBT.getText();if("增加".equals(text)){newAddView(mainView);}elseif("删除".equals(text)){int[] ids = mainView.getIds();for(int id : ids){deleteOp(id);}//获取所有数据并重新显示TableModel.updateModel(getAllData());}elseif("修改".equals(text)){int[] ids = mainView.getIds();if(ids.length ==0){//报错窗口JOptionPane.showMessageDialog(mainView,"请选择需要修改的数据段");return;}if(ids.length !=1){//报错窗口JOptionPane.showMessageDialog(mainView,"一次只能修改一条信息!!!");return;}newUpdateView(mainView, ids[0]);}elseif("时间查询".equals(text)){String from = mainView.getSearchTxt1().getText();Stringto= mainView.getSearchTxt2().getText();//验证合法if(!timeLegal(from,to)){//报错窗口JOptionPane.showMessageDialog(mainView,"查询格式出错,请对照hh:mm:ss格式");return;}Vector<Vector<Object>> data =newVector<>();TimeSearch(data, from,to);//更新table数据TableModel.updateModel(data);}elseif("添加".equals(text)){String name = addView.getNameTxt().getText();String age = addView.getAgeTxt().getText();String gender = addView.getComboBox1().getSelectedItem().toString();String sort = addView.getComboBox2().getSelectedItem().toString();String in = addView.getInTxt().getText();String out = addView.getOutTxt().getText();if(!inLegal(name, age, in)){//报错窗口JOptionPane.showMessageDialog(mainView,"信息不能为空!!!");return;}if(!ageLegal(age)){//报错窗口JOptionPane.showMessageDialog(mainView,"年龄输入错误");return;}if(!timeLegal(in, out)){//报错窗口JOptionPane.showMessageDialog(mainView,"时间格式错误,请对照hh:mm:ss格式");return;}if(!isSame(name)){//报错窗口JOptionPane.showMessageDialog(mainView,"不可以重复添加哦");return;}Tourist t =newTourist(name, age, gender, sort, in, out);addOp(t);//窗口JOptionPane.showMessageDialog(mainView,"添加成功!!!");//获取所有数据并重新显示TableModel.updateModel(getAllData());}elseif("确认修改".equals(text)){String id = updateView.getIdTxt().getText();String name = updateView.getNameTxt().getText();String age = updateView.getAgeTxt().getText();String gender = updateView.getComboBox1().getSelectedItem().toString();String sort = updateView.getComboBox2().getSelectedItem().toString();String in = updateView.getInTxt().getText();String out = updateView.getOutTxt().getText();if(!inLegal(name, age, in)){//报错窗口JOptionPane.showMessageDialog(mainView,"信息不能为空!!!");return;}if(!ageLegal(age)){//报错窗口JOptionPane.showMessageDialog(mainView,"年龄输入错误");return;}if(!timeLegal(in, out)){//报错窗口JOptionPane.showMessageDialog(mainView,"时间格式错误,请对照hh:mm:ss格式");return;}Tourist t =newTourist(id, name, age, gender, sort, in, out);updateOp(t);//窗口JOptionPane.showMessageDialog(mainView,"修改成功!!!");//获取所有数据并重新显示TableModel.updateModel(getAllData());}elseif("姓名查询".equals(text)){String name = mainView.getSearchTxt1().getText();Vector<Vector<Object>> data =newVector<>();NameSearch(data, name);//更新table数据TableModel.updateModel(data);}}publicbooleanisSame(String name ){String sql ="select * from tourist";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){returnfalse;}
ps = con.prepareStatement(sql);
rs = ps.executeQuery();//遍历查看是否有这个人了 别重复添加while(rs.next()){String s = rs.getString("name");if(name.equals(s)){returnfalse;}}}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}returntrue;}privatebooleaninLegal(String name,String age,String in){return!(name.equals("")|| age.equals("")|| in.equals(""));}privatebooleanageLegal(String age){for(int i =0; i < age.length(); i++){if(!(age.charAt(i)>='0'&& age.charAt(i)<='9')){returnfalse;}}int parseInt =Integer.parseInt(age);if(parseInt >=110){returnfalse;}returntrue;}privatebooleantimeLegal(String from,Stringto){boolean ff =true;boolean tt =true;if(!from.equals("")){String[] f = from.split(":");if(f.length !=3){returnfalse;}int f1 =Integer.parseInt(f[0]);int f2 =Integer.parseInt(f[1]);int f3 =Integer.parseInt(f[2]);
ff = f1 >=0&& f1 <24&& f2 >=0&& f2 <60&& f3 >=0&& f3 <60;}if(!to.equals("")){String[] t =to.split(":");if(t.length !=3){returnfalse;}int t1 =Integer.parseInt(t[0]);int t2 =Integer.parseInt(t[1]);int t3 =Integer.parseInt(t[2]);
tt = t1 >=0&& t1 <24&& t2 >=0&& t2 <60&& t3 >=0&& t3 <60;}return ff && tt;}//时间区间查询publicstaticvoidTimeSearch(Vector<Vector<Object>> data,String from,Stringto){if(from.equals("")){
from ="00:00:00";}if(to.equals("")){to="23:59:59";}String sql ="select * from tourist where in_time >= ? and out_time <= ?";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){return;}
ps = con.prepareStatement(sql);
ps.setString(1, from);
ps.setString(2,to);
rs = ps.executeQuery();while(rs.next()){Vector<Object> d =newVector<>();
d.add(rs.getString("id"));
d.add(rs.getString("name"));
d.add(rs.getString("age"));
d.add(rs.getString("gender"));
d.add(rs.getString("sort"));
d.add(rs.getString("in_time"));
d.add(rs.getString("out_time"));
data.add(d);}}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}}//获取所有的数据publicstaticVector<Vector<Object>>getAllData(){Vector<Vector<Object>> data =newVector<>();String sql ="select * from tourist";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){returnnull;}
ps = con.prepareStatement(sql);
rs = ps.executeQuery();while(rs.next()){Vector<Object> d =newVector<>();
d.add(rs.getString("id"));
d.add(rs.getString("name"));
d.add(rs.getString("age"));
d.add(rs.getString("gender"));
d.add(rs.getString("sort"));
d.add(rs.getString("in_time"));
d.add(rs.getString("out_time"));
data.add(d);}}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}return data;}//添加publicstaticvoidaddOp(Tourist t){String sql ="insert into tourist(name,age,gender,sort,in_time,out_time) values(?,?,?,?,?,?);";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){return;}
ps = con.prepareStatement(sql);
ps.setString(1, t.getName());
ps.setString(2, t.getAge());
ps.setString(3, t.getGender());
ps.setString(4, t.getSort());
ps.setString(5, t.getInTime());if(t.getOutTime().equals("")){
ps.setString(6,null);}else{
ps.setString(6, t.getOutTime());}
ps.execute();}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}}//修改 //没做完 打点publicstaticvoidupdateOp(Tourist t){String sql ="update tourist set name = ?, age = ?, gender = ?, sort = ?,in_time = ?, out_time = ? where id = ?";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){return;}
ps = con.prepareStatement(sql);
ps.setString(1, t.getName());
ps.setString(2, t.getAge());
ps.setString(3, t.getGender());
ps.setString(4, t.getSort());
ps.setString(5, t.getInTime());
ps.setString(6, t.getOutTime());
ps.setString(7, t.getId());
ps.executeUpdate();}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}}//删除publicstaticvoiddeleteOp(int id){String sql ="delete from tourist where id = ?";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){return;}
ps = con.prepareStatement(sql);
ps.setString(1,String.valueOf(id));
ps.executeUpdate();}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}}//姓名模糊查询publicstaticvoidNameSearch(Vector<Vector<Object>> data,String name){String sql ="select * from tourist where name like ?";Connection con =null;PreparedStatement ps =null;ResultSet rs =null;try{
con =DBUtil.getConnection();if(con ==null){return;}
ps = con.prepareStatement(sql);
ps.setString(1,"%"+ name +"%");
rs = ps.executeQuery();while(rs.next()){Vector<Object> d =newVector<>();
d.add(rs.getString("id"));
d.add(rs.getString("name"));
d.add(rs.getString("age"));
d.add(rs.getString("gender"));
d.add(rs.getString("sort"));
d.add(rs.getString("in_time"));
d.add(rs.getString("out_time"));
data.add(d);}}catch(SQLException throwables){
throwables.printStackTrace();}finally{//按顺序关闭资源DBUtil.closeRs(rs);DBUtil.closePs(ps);DBUtil.closeCon(con);}}}
DBUtil:
packageUtil;//JDBC连接importjava.sql.*;publicclassDBUtil{privatestaticfinalStringURL="jdbc:mysql://localhost:3306/park?useUnicode=true&characterEncoding=UTF-8&userSSL=true&serverTimezone=GMT%2B8";privatestaticfinalStringDRIVER="com.mysql.cj.jdbc.Driver";//写你自己的账号密码privatestaticfinalStringUSER_NAME="root";privatestaticfinalStringPWD="";static{try{//用来加载"com.mysql.jdbc.Driver"类 执行它里面的静态代码块Class.forName(DRIVER);}catch(ClassNotFoundException e){
e.printStackTrace();}}//建立连接publicstaticConnectiongetConnection(){try{returnDriverManager.getConnection(URL,USER_NAME,PWD);}catch(SQLException throwables){
throwables.printStackTrace();}returnnull;}//关闭各种资源publicstaticvoidcloseCon(Connection connection){if(connection !=null){try{
connection.close();}catch(SQLException throwables){
throwables.printStackTrace();}}}publicstaticvoid closePs (PreparedStatement ps){if(ps !=null){try{
ps.close();}catch(SQLException throwables){
throwables.printStackTrace();}}}publicstaticvoidcloseRs(ResultSet rs){if(rs !=null){try{
rs.close();}catch(SQLException throwables){
throwables.printStackTrace();}}}}
Main:
importJFrame.LoginView;publicclassMain{publicstaticvoidmain(String[] args){newLoginView();}}
数据库:
/*
Navicat Premium Data Transfer
Source Server : 本机MySQL
Source Server Type : MySQL
Source Server Version : 80013
Source Host : localhost:3306
Source Schema : park
Target Server Type : MySQL
Target Server Version : 80013
File Encoding : 65001
Date: 08/12/2023 21:43:55
*/SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS =0;-- ------------------------------ Table structure for manager-- ----------------------------DROPTABLEIFEXISTS`manager`;CREATETABLE`manager`(`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'主键',`admin`varchar(255)CHARACTERSET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOTNULLCOMMENT'用户名',`pwd`varchar(255)CHARACTERSET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOTNULLCOMMENT'密码',PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBCHARACTERSET= utf8mb4 COLLATE= utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS =1;
/*
Navicat Premium Data Transfer
Source Server : 本机MySQL
Source Server Type : MySQL
Source Server Version : 80013
Source Host : localhost:3306
Source Schema : park
Target Server Type : MySQL
Target Server Version : 80013
File Encoding : 65001
Date: 08/12/2023 21:56:59
*/SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS =0;-- ------------------------------ Table structure for tourist-- ----------------------------DROPTABLEIFEXISTS`tourist`;CREATETABLE`tourist`(`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'ID',`name`varchar(255)CHARACTERSET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOTNULLCOMMENT'游客名',`age`int(11)NOTNULLCOMMENT'年龄',`gender`varchar(255)CHARACTERSET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOTNULLCOMMENT'性别',`sort`varchar(11)CHARACTERSET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOTNULLCOMMENT'分类分类',`in_time`time(0)NOTNULLCOMMENT'进入时间',`out_time`time(0)NOTNULLCOMMENT'出去时间',PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBCHARACTERSET= utf8mb4 COLLATE= utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS =1;
版权归原作者 木木是木木 所有, 如有侵权,请联系我们删除。