写了蛮久的综合课设大作业,今天分享一下下,我们需要创建的是一个maven项目,该作业使用到了 Java + MySQL + GUI 实现,具体可见下面。
一、展示:
登陆界面:
主界面:
添加界面:
修改界面:
二、目录:
创建的maven项目初始样子:
创建好包、类之后:
三、代码:
Tourist:
package Class;
//游客类
public class Tourist {
String id;
String name;
String age;
String gender;
String sort;
String inTime;
String outTime;
public Tourist(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;
}
public Tourist(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;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public String getGender() {
return gender;
}
public String getSort() {
return sort;
}
public String getInTime() {
return inTime;
}
public String getOutTime() {
return outTime;
}
}
AddView :
package JFrame;
//添加界面
import Operate.TouristOperate;
import javax.swing.*;
import java.awt.*;
public class AddView extends JDialog {
JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.CENTER,10,20));//水平间距垂直间距调节
JLabel nameLab = new JLabel("姓名:",JLabel.RIGHT);//右对齐
JTextField nameTxt = new JTextField();
JLabel ageLab = new JLabel("年龄:",JLabel.RIGHT);
JTextField ageTxt = new JTextField();
JLabel genderLab = new JLabel("性别:",JLabel.RIGHT);
// 创建下拉框
JComboBox comboBox1 = new JComboBox();
JLabel sortLab = new JLabel("人群类型:",JLabel.RIGHT);
// 创建下拉框
JComboBox comboBox2 = new JComboBox();
// 绑定下拉框选项
String[] Array = {"少年", "青年", "中年", "老年"};
JLabel inLab = new JLabel("入园时间:",JLabel.RIGHT);
JTextField inTxt = new JTextField();
JLabel outLab = new JLabel("离园时间:",JLabel.RIGHT);
JTextField outTxt = new JTextField();
JButton addBt = new JButton("添加");
//游客操作按钮监听
TouristOperate touristOperate;
public AddView(MainView mainView) {
//该窗体以来mainView
super(mainView, "信息添加", true);
touristOperate = new TouristOperate(this);
nameLab.setPreferredSize(new Dimension(80,30));
jPanel.add(nameLab);
nameTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(nameTxt);
ageLab.setPreferredSize(new Dimension(80,30));
jPanel.add(ageLab);
ageTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(ageTxt);
genderLab.setPreferredSize(new Dimension(80,30));
jPanel.add(genderLab);
comboBox1.addItem("男");
comboBox1.addItem("女");
jPanel.add(comboBox1);
//选项框
sortLab.setPreferredSize(new Dimension(80,30));
jPanel.add(sortLab);
for (String s : Array) {
comboBox2.addItem(s);
}
jPanel.add(comboBox2);
inLab.setPreferredSize(new Dimension(80,30));
jPanel.add(inLab);
inTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(inTxt);
outLab.setPreferredSize(new Dimension(80,30));
jPanel.add(outLab);
outTxt.setPreferredSize(new Dimension(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);//可视化
}
public JTextField getNameTxt() {
return nameTxt;
}
public JTextField getAgeTxt() {
return ageTxt;
}
public JComboBox getComboBox1() {
return comboBox1;
}
public JComboBox getComboBox2() {
return comboBox2;
}
public JTextField getInTxt() {
return inTxt;
}
public JTextField getOutTxt() {
return outTxt;
}
}
J_Table :
package JFrame;
//表格
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import java.awt.*;
public class J_Table extends JTable {
public J_Table() {
//设置表头
JTableHeader tableHeader = getTableHeader();
tableHeader.setFont(new Font(null, Font.BOLD, 22));//字形 粗细 大小
tableHeader.setForeground(Color.RED);//字体颜色
//设置表格体
setFont(new Font(null, Font.PLAIN, 18));
setRowHeight(25);//设置表格行高
setForeground(Color.black);
setGridColor(Color.BLACK);//线条
//设置多行选择
getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//表格字体居中
DefaultTableCellRenderer r=new DefaultTableCellRenderer();
r.setHorizontalAlignment(JLabel.CENTER);
setDefaultRenderer(Object.class,r);
}
}
LoginView:登录面板里面右上角有一个小图标,是通过 URL url = LoginView.class.getClassLoader().getResource("qq.jpg")
实现的,图片我没给,可以选择自己喜欢的一张拖进resources 包下,然后更改对应路径名就可以了。
package JFrame;
//登陆界面
import Operate.LoginOperate;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
public class LoginView extends JFrame {
JLabel nameLab = new JLabel("Java -皇家公园管理系统", JLabel.CENTER);
SpringLayout springLayout = new SpringLayout();//弹簧布局
//中心面板
JPanel centerPanel = new JPanel(springLayout);
//用户名
JLabel userNameLab = new JLabel("用户名:");
JTextField userTxt = new JTextField();
//密码
JLabel passWordLab = new JLabel("密码:");
JPasswordField passWordTxt = new JPasswordField();
//按钮
JButton loginBt = new JButton("登录");
JButton resetBt = new JButton("重置");
//增加系统托盘
TrayIcon trayIcon;
SystemTray systemTray;
//按钮事件处理
LoginOperate loginHandler;
//初始化
public LoginView() {
super("公园管理系统登录");
Container contentPane = getContentPane();
//new对象才能操作
this.loginHandler = new LoginOperate(this);
//设置字体大小等
nameLab.setFont(new Font("华文行楷", Font.PLAIN, 40));
nameLab.setPreferredSize(new Dimension(0, 120));
Font centerFont = new Font("楷体", Font.PLAIN, 20);
userNameLab.setFont(centerFont);
userTxt.setPreferredSize(new Dimension(200, 30));//设置大小
passWordLab.setFont(centerFont);
passWordTxt.setPreferredSize(new Dimension(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);
//弹簧布局
//布局userNameLab
Spring 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 = new TrayIcon(new ImageIcon(url).getImage());
trayIcon.setImageAutoSize(true);
try {
systemTray.add(trayIcon);
} catch (AWTException e) {
e.printStackTrace();
}
//最小化时销毁窗口
this.addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(WindowEvent e) {
LoginView.this.dispose();
}
});
//托盘事件监听
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int clickCount = e.getClickCount();
if (clickCount == 1) {
LoginView.this.setExtendedState(JFrame.NORMAL);
}
LoginView.this.setVisible(true);//可视化
}
});
}
//常规设置 !!!:放最后 小心吃亏
setIconImage(new ImageIcon(url).getImage());
setSize(600, 400);//设置大小
setLocationRelativeTo(null);//居中
setDefaultCloseOperation(EXIT_ON_CLOSE);//点击关闭关闭程序
setResizable(false);//大小不可变
setVisible(true);//可视化
}
public JTextField getUserTxt() {
return userTxt;
}
public void setUserTxt(JTextField userTxt) {
this.userTxt = userTxt;
}
public JPasswordField getPassWordTxt() {
return passWordTxt;
}
public void setPassWordTxt(JPasswordField passWordTxt) {
this.passWordTxt = passWordTxt;
}
}
MainView :
package JFrame;
//主界面
import Operate.TouristOperate;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.util.Vector;
public class MainView extends JFrame {
JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton addBt = new JButton("增加");
JButton updateBt = new JButton("修改");
JButton delBt = new JButton("删除");
JTextField searchTxt1 = new JTextField(10);
JLabel line = new JLabel("—");
JTextField searchTxt2 = new JTextField(10);
JButton searchBT = new JButton("时间查询");
JButton searchName = new JButton("姓名查询");
// JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
// JButton preBt = new JButton("上一页");
// JButton nextBt = new JButton("下一页");
J_Table table = new J_Table();
//游客操作按钮监听
TouristOperate touristOperate;
public MainView() {
super("公园管理系统");
Container contentPane = getContentPane();
//new对象了才能进行操作
this.touristOperate = new TouristOperate(this);
//上方按钮
layoutNorth(contentPane);
//中间表格题
layoutCenter(contentPane);
// //下方按钮
// layoutSouth(contentPane);
//常规设置 !!!:放最后 小心吃亏
URL url = LoginView.class.getClassLoader().getResource("qq.jpg");
setIconImage(new ImageIcon(url).getImage());
setSize(1300, 800);//设置大小
setLocationRelativeTo(null);//居中
setDefaultCloseOperation(EXIT_ON_CLOSE);//点击关闭关闭程序
setResizable(false);//大小不可变
setVisible(true);//可视化
}
private void layoutCenter(Container contentPane) {
Vector<Vector<Object>> data = TouristOperate.getAllData();
//更新table数据
TableModel.updateModel(data);
TableModel tableModel = TableModel.assembleModel(data);
table.setModel(tableModel);
JScrollPane jScrollPane = new JScrollPane(table);
contentPane.add(jScrollPane, BorderLayout.CENTER);
}
// private void layoutSouth(Container contentPane) {
// southPanel.add(preBt);
// southPanel.add(nextBt);
// contentPane.add(southPanel, BorderLayout.SOUTH);
// }
private void layoutNorth(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(new Dimension(200, 30));
searchTxt2.setPreferredSize(new Dimension(200, 30));
northPanel.add(searchBT);
northPanel.add(searchName);
contentPane.add(northPanel, BorderLayout.NORTH);
}
public JTextField getSearchTxt1() {
return searchTxt1;
}
public JTextField getSearchTxt2() {
return searchTxt2;
}
//获取选中的行的id用来进行修改和删除
public int[] getIds() {
int[] selectedRows = table.getSelectedRows();
int[] idx = new int[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 :
package JFrame;
//table 模型
import javax.swing.table.DefaultTableModel;
import java.util.Vector;
public class TableModel extends DefaultTableModel {
static Vector<String> cloumns = new Vector<>();
private static TableModel tableModel = new TableModel();
static {
cloumns.addElement("编号");
cloumns.addElement("姓名");
cloumns.addElement("年龄");
cloumns.addElement("性别");
cloumns.addElement("人群类型");
cloumns.addElement("入园时间");
cloumns.addElement("离园时间");
}
public TableModel() {
super(null, cloumns);
}
public static TableModel assembleModel(Vector<Vector<Object>> data) {
tableModel.setDataVector(data, cloumns);
tableModel.getColumnClass(200);
return tableModel;
}
//更新数据表数据
public static void updateModel(Vector<Vector<Object>> data) {
tableModel.setDataVector(data, cloumns);
}
public static Vector<String> getCloumns() {
return cloumns;
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
UpdateView :
package JFrame;
//更新界面
import Operate.TouristOperate;
import Util.DBUtil;
import Class.*;
import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UpdateView extends JDialog {
JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 20));//水平间距垂直间距调节
JLabel idLab = new JLabel("编号:", JLabel.RIGHT);
JTextField idTxt = new JTextField();
JLabel nameLab = new JLabel("姓名:", JLabel.RIGHT);//右对齐
JTextField nameTxt = new JTextField();
JLabel ageLab = new JLabel("年龄:", JLabel.RIGHT);
JTextField ageTxt = new JTextField();
JLabel genderLab = new JLabel("性别:", JLabel.RIGHT);
// 创建下拉框
JComboBox comboBox1 = new JComboBox();
JLabel sortLab = new JLabel("人群类型:", JLabel.RIGHT);
// 创建下拉框
JComboBox comboBox2 = new JComboBox();
// 绑定下拉框选项
String[] Array = {"少年", "青年", "中年", "老年"};
JLabel inLab = new JLabel("入园时间:", JLabel.RIGHT);
JTextField inTxt = new JTextField();
JLabel outLab = new JLabel("离园时间:", JLabel.RIGHT);
JTextField outTxt = new JTextField();
JButton addBt = new JButton("确认修改");
//游客操作按钮监听
TouristOperate touristOperate;
int id = -1;
public UpdateView(MainView mainView, int id) {
//该窗体以来mainView
super(mainView, "信息修改", true);
touristOperate = new TouristOperate(this);
this.id = id;
Tourist t = searchId(id);
idLab.setPreferredSize(new Dimension(80, 30));
jPanel.add(idLab);
idTxt.setPreferredSize(new Dimension(200, 30));
idTxt.setText(t.getId());
idTxt.setEditable(false);//设置文本域不能编辑 该处为主键 不可修改
jPanel.add(idTxt);
nameLab.setPreferredSize(new Dimension(80, 30));
jPanel.add(nameLab);
nameTxt.setPreferredSize(new Dimension(200, 30));
nameTxt.setText(t.getName());
jPanel.add(nameTxt);
ageLab.setPreferredSize(new Dimension(80, 30));
jPanel.add(ageLab);
ageTxt.setPreferredSize(new Dimension(200, 30));
ageTxt.setText(t.getAge());
jPanel.add(ageTxt);
genderLab.setPreferredSize(new Dimension(80, 30));
jPanel.add(genderLab);
comboBox1.addItem("男");
comboBox1.addItem("女");
comboBox1.setSelectedItem(t.getGender());
jPanel.add(comboBox1);
//选项框
sortLab.setPreferredSize(new Dimension(80, 30));
jPanel.add(sortLab);
for (String s : Array) {
comboBox2.addItem(s);
}
comboBox2.setSelectedItem(t.getSort());
jPanel.add(comboBox2);
inLab.setPreferredSize(new Dimension(80, 30));
jPanel.add(inLab);
inTxt.setPreferredSize(new Dimension(200, 30));
inTxt.setText(t.getInTime());
jPanel.add(inTxt);
outLab.setPreferredSize(new Dimension(80, 30));
jPanel.add(outLab);
outTxt.setPreferredSize(new Dimension(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查询
private Tourist searchId(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) {
return null;
}
ps = con.prepareStatement(sql);
ps.setString(1, String.valueOf(id));
rs = ps.executeQuery();
while (rs.next()) {
Tourist t = new Tourist(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);
}
return null;
}
public JTextField getIdTxt() {
return idTxt;
}
public JTextField getNameTxt() {
return nameTxt;
}
public JTextField getAgeTxt() {
return ageTxt;
}
public JComboBox getComboBox1() {
return comboBox1;
}
public JComboBox getComboBox2() {
return comboBox2;
}
public JTextField getInTxt() {
return inTxt;
}
public JTextField getOutTxt() {
return outTxt;
}
}
AdminOp:
package Operate;
//管理员信息
import Util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AdminOp {
public static boolean isLegal(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) {
return false;
}
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)) {
return true;
}
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
//按顺序关闭资源
DBUtil.closeRs(rs);
DBUtil.closePs(ps);
DBUtil.closeCon(con);
}
return false;
}
}
LoginOperate :
package Operate;
//登录操作
import JFrame.LoginView;
import JFrame.MainView;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginOperate implements ActionListener {
public LoginView loginView;
public LoginOperate(LoginView loginView) {
this.loginView = loginView;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton JBT = (JButton) e.getSource();
String text = JBT.getText();
if ("登录".equals(text)) {
login();
} else if ("重置".equals(text)) {
loginView.getUserTxt().setText("");
loginView.getPassWordTxt().setText("");
}
}
private void login() {
String user = loginView.getUserTxt().getText();
String passWord = new String(loginView.getPassWordTxt().getPassword());
//查询数据库是否有该用户
boolean flag = AdminOp.isLegal(user, passWord);
if (flag) {
//跳转主界面 and 销魂登录界面
new MainView();
loginView.dispose();
} else {
//报错窗口
JOptionPane.showMessageDialog(loginView, "用户名密码错误!!!");
}
}
}
TouristOperate:
package Operate;
//游客操作
import Util.DBUtil;
import JFrame.*;
import Class.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
public class TouristOperate implements ActionListener {
public MainView mainView;
public AddView addView;
public UpdateView updateView;
public TouristOperate(MainView mainView) {
this.mainView = mainView;
}
public TouristOperate(AddView addView) {
this.addView = addView;
}
public TouristOperate(UpdateView updateView) {
this.updateView = updateView;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton JBT = (JButton) e.getSource();
String text = JBT.getText();
if ("增加".equals(text)) {
new AddView(mainView);
} else if ("删除".equals(text)) {
int[] ids = mainView.getIds();
for (int id : ids) {
deleteOp(id);
}
//获取所有数据并重新显示
TableModel.updateModel(getAllData());
} else if ("修改".equals(text)) {
int[] ids = mainView.getIds();
if (ids.length == 0) {
//报错窗口
JOptionPane.showMessageDialog(mainView, "请选择需要修改的数据段");
return;
}
if (ids.length != 1) {
//报错窗口
JOptionPane.showMessageDialog(mainView, "一次只能修改一条信息!!!");
return;
}
new UpdateView(mainView, ids[0]);
} else if ("时间查询".equals(text)) {
String from = mainView.getSearchTxt1().getText();
String to = mainView.getSearchTxt2().getText();
//验证合法
if (!timeLegal(from, to)) {
//报错窗口
JOptionPane.showMessageDialog(mainView, "查询格式出错,请对照hh:mm:ss格式");
return;
}
Vector<Vector<Object>> data = new Vector<>();
TimeSearch(data, from, to);
//更新table数据
TableModel.updateModel(data);
} else if ("添加".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 = new Tourist(name, age, gender, sort, in, out);
addOp(t);
//窗口
JOptionPane.showMessageDialog(mainView, "添加成功!!!");
//获取所有数据并重新显示
TableModel.updateModel(getAllData());
} else if ("确认修改".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 = new Tourist(id, name, age, gender, sort, in, out);
updateOp(t);
//窗口
JOptionPane.showMessageDialog(mainView, "修改成功!!!");
//获取所有数据并重新显示
TableModel.updateModel(getAllData());
} else if ("姓名查询".equals(text)) {
String name = mainView.getSearchTxt1().getText();
Vector<Vector<Object>> data = new Vector<>();
NameSearch(data, name);
//更新table数据
TableModel.updateModel(data);
}
}
public boolean isSame(String name ) {
String sql = "select * from tourist";
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBUtil.getConnection();
if (con == null) {
return false;
}
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
//遍历查看是否有这个人了 别重复添加
while (rs.next()) {
String s = rs.getString("name");
if (name.equals(s)) {
return false;
}
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
//按顺序关闭资源
DBUtil.closeRs(rs);
DBUtil.closePs(ps);
DBUtil.closeCon(con);
}
return true;
}
private boolean inLegal(String name, String age, String in) {
return !(name.equals("") || age.equals("") || in.equals(""));
}
private boolean ageLegal(String age) {
for (int i = 0; i < age.length(); i++) {
if (!(age.charAt(i) >= '0' && age.charAt(i) <= '9')) {
return false;
}
}
int parseInt = Integer.parseInt(age);
if (parseInt >= 110) {
return false;
}
return true;
}
private boolean timeLegal(String from, String to) {
boolean ff = true;
boolean tt = true;
if (!from.equals("")) {
String[] f = from.split(":");
if (f.length != 3) {
return false;
}
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) {
return false;
}
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;
}
//时间区间查询
public static void TimeSearch(Vector<Vector<Object>> data, String from, String to) {
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 = new Vector<>();
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);
}
}
//获取所有的数据
public static Vector<Vector<Object>> getAllData() {
Vector<Vector<Object>> data = new Vector<>();
String sql = "select * from tourist";
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBUtil.getConnection();
if (con == null) {
return null;
}
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Vector<Object> d = new Vector<>();
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;
}
//添加
public static void addOp(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);
}
}
//修改 //没做完 打点
public static void updateOp(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);
}
}
//删除
public static void deleteOp(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);
}
}
//姓名模糊查询
public static void NameSearch(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 = new Vector<>();
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:
package Util;
//JDBC连接
import java.sql.*;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/park?useUnicode=true&characterEncoding=UTF-8&userSSL=true&serverTimezone=GMT%2B8";
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
//写你自己的账号密码
private static final String USER_NAME = "root";
private static final String PWD = "";
static {
try {
//用来加载"com.mysql.jdbc.Driver"类 执行它里面的静态代码块
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//建立连接
public static Connection getConnection() {
try {
return DriverManager.getConnection(URL, USER_NAME, PWD);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
//关闭各种资源
public static void closeCon(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void closePs (PreparedStatement ps) {
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void closeRs(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
Main:
import JFrame.LoginView;
public class Main {
public static void main(String[] args) {
new LoginView();
}
}
数据库:
/*
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
-- ----------------------------
DROP TABLE IF EXISTS `manager`;
CREATE TABLE `manager` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`admin` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户名',
`pwd` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '密码',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = 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
-- ----------------------------
DROP TABLE IF EXISTS `tourist`;
CREATE TABLE `tourist` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '游客名',
`age` int(11) NOT NULL COMMENT '年龄',
`gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '性别',
`sort` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '分类分类',
`in_time` time(0) NOT NULL COMMENT '进入时间',
`out_time` time(0) NOT NULL COMMENT '出去时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;