欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码及步骤

程序员文章站 2022-10-04 10:38:16
(原创)JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码)一、先看项目运行效果:管理员登录:管理员主页:新增:查改删:二、代码结构三、代码(从上往下):3.1dao包3.1.1AdminDaopublic class AdminDao {//读取管理员数据public Map readAdmin() {Map map = new HashMap&...

(原创)JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码)

一、先看项目运行效果:

管理员登录:
JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码及步骤
管理员主页:
JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码及步骤
新增:
JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码及步骤
查改删:

JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码及步骤
二、代码结构
JAVA-学生管理系统(最简单的SWING+IO读写文件持久化数据)详细代码及步骤
三、代码(从上往下):
3.1 dao包

3.1.1 AdminDao

public class AdminDao {
	//读取管理员数据
	public Map<String, String> readAdmin() {
		Map<String, String> map = new HashMap<>();
        try (BufferedReader br = new BufferedReader(new FileReader("admin.txt"))) {
            String line = br.readLine();
            String[] textData = null;
            while (line != null) {
                textData = line.split("\\,");
                String name = textData[0];
                String password = textData[1];
                map.put(name, password);
                line = br.readLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}

3.1.2 StudentDao

public class StudentDao {
	//读取学生数据
	public ArrayList<Student> readStudent() {
		ArrayList<Student> list = new ArrayList<>();
		try (BufferedReader br = new BufferedReader(new FileReader("student.txt"))) {
			String line = br.readLine();
			String[] textData = null;
			while (line != null) {
				textData = line.split("\\,");
				String name = textData[0];
				String age = textData[1];
				String address = textData[2];
				String tel = textData[3];
				Student student = new Student(0, name, age, address, tel);
				list.add(student);
				line = br.readLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}
	//写入学生数据
	public int writeStudent(Student student) {
		ArrayList<Student> list = readStudent();
		list.add(student);
		int num = 0;
		try {
			FileWriter fileWriter = new FileWriter("student.txt");
			for (int i = 0; i < list.size(); i++) {
				Student stu = list.get(i);
				fileWriter.write(
						stu.getName() + "," + stu.getAge() + "," + stu.getAddress() + "," + stu.getTel() + "\r\n");
			}
			fileWriter.flush();
			fileWriter.close();
			num = 1;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return num;
	}
	//删除学生
	public int delStudent(String name) {
		ArrayList<Student> list = readStudent();
		int num = 0;
		for (int i = 0; i < list.size(); i++) {
			if (name.equals(list.get(i).getName())) {
				list.remove(i);
			}
		}
		try {
			FileWriter fileWriter = new FileWriter("student.txt");
			for (int i = 0; i < list.size(); i++) {
				Student stu = list.get(i);
				fileWriter.write(
						stu.getName() + "," + stu.getAge() + "," + stu.getAddress() + "," + stu.getTel() + "\r\n");
			}
			fileWriter.flush();
			fileWriter.close();
			num = 1;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return num;
	}
	//按名字查找学生
	public ArrayList<Student> findStudent(String name) {
		ArrayList<Student> list = readStudent();
		ArrayList<Student> newlist = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getName().contains(name)){
				newlist.add(list.get(i));
			}
		}	
		return newlist;
	}
}

3.2 model
3.2.1 Admin

//管理员实体类
public class Admin {
	private int id;
	private String name;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Admin(int id, String name, String password) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
	}
	public Admin() {
		super();
	}
	
}

3.2.2 student

//学生实体类
public class Student {
	private int id;
	private String name;	//姓名
	private String age;		//年龄
	private String address;	//地址
	private String tel;		//电话
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public Student(int id, String name, String age, String address, String tel) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
		this.tel = tel;
	}
	public Student() {
		super();
	}
	
	
}

3.3 util包
3.3.1 StringUtil

public class StringUtil {
	//判空
	public static Boolean isNull(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}
	
	//判断日期格式
	public static boolean isValidDate(String str) {
		boolean convertSuccess = true;
		// 指定日期格式为四位年/两位月份/两位日期
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			// 设置lenient为false.
			// 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
			convertSuccess = false;
		}
		return convertSuccess;
	}

	//判断是否为数字
	public static boolean isNumeric(String str) {
		String reg = "^[0-9]+(.[0-9]+)?$";

        return str.matches(reg);
	}

}

3.4 view
3.4.1 AddStudent

public class AddStudent extends JInternalFrame {
	private JTextField name;
	private JTextField age;
	private JTextField address;
	private JTextField tel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AddStudent frame = new AddStudent();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public AddStudent() {
		setIconifiable(true);
		setClosable(true);
		setTitle("新增学生");
		setBounds(100, 100, 260, 319);
		
		JLabel label = new JLabel("姓名:");
		
		name = new JTextField();
		name.setColumns(10);
		
		JLabel label_1 = new JLabel("年龄:");
		
		age = new JTextField();
		age.setColumns(10);
		
		JLabel label_2 = new JLabel("住址:");
		
		address = new JTextField();
		address.setColumns(10);
		
		JLabel label_3 = new JLabel("电话:");
		
		tel = new JTextField();
		tel.setColumns(10);
		
		JButton button = new JButton("提交");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				submit();
			}
		});
		button.setIcon(new ImageIcon(AddStudent.class.getResource("/images/submit.png")));
		
		JButton button_1 = new JButton("重置");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				reset();
			}
		});
		button_1.setIcon(new ImageIcon(AddStudent.class.getResource("/images/reset.png")));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(38)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(label_3)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(tel))
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(label_2)
									.addPreferredGap(ComponentPlacement.UNRELATED)
									.addComponent(address))
								.addGroup(groupLayout.createSequentialGroup()
									.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
										.addComponent(label_1)
										.addComponent(label))
									.addPreferredGap(ComponentPlacement.RELATED)
									.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
										.addComponent(age)
										.addComponent(name, GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)))))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(29)
							.addComponent(button)
							.addGap(27)
							.addComponent(button_1)))
					.addContainerGap(34, Short.MAX_VALUE))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(45)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(label)
						.addComponent(name, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(18)
							.addComponent(label_1))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(17)
							.addComponent(age, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
					.addGap(18)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(label_2)
						.addComponent(address, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(18)
							.addComponent(label_3))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(19)
							.addComponent(tel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addPreferredGap(ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
							.addComponent(button)
							.addGap(44))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(37)
							.addComponent(button_1)
							.addContainerGap())))
		);
		getContentPane().setLayout(groupLayout);

	}
	
	//提交
	private void submit() {
		// TODO Auto-generated method stub
		String name = this.name.getText();
		String age = this.age.getText();
		String address = this.address.getText();
		String tel = this.tel.getText();
		
		if (StringUtil.isNull(name)) {
			JOptionPane.showMessageDialog(null, "姓名不能为空!");
			return;
		}
		if (StringUtil.isNull(age)) {
			JOptionPane.showMessageDialog(null, "年龄不能为空!");
			return;
		}
		if (StringUtil.isNull(address)) {
			JOptionPane.showMessageDialog(null, "地址不能为空!");
			return;
		}
		if (StringUtil.isNull(tel)) {
			JOptionPane.showMessageDialog(null, "电话不能为空!");
			return;
		}
		
		Student student = new Student(0, name, age, address, tel);
		StudentDao studentDao = new StudentDao();
		int num = studentDao.writeStudent(student);
		if (num != 0) {
			JOptionPane.showMessageDialog(null, "新增成功!");
			dispose();
		}else {
			JOptionPane.showMessageDialog(null, "新增失败!");
		}
		
	}
	
	//清空
	private void reset() {
		// TODO Auto-generated method stub
		this.name.setText("");
		this.age.setText("");
		this.address.setText("");
		this.tel.setText("");
	}
}

3.4.2 AdminMainPage

public class AdminMainPage extends JFrame {

	private JPanel contentPane;
	private JDesktopPane table;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AdminMainPage frame = new AdminMainPage();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public AdminMainPage() {
		setTitle("管理员主页");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 931, 705);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu menu = new JMenu("新增学生信息");
		menu.setIcon(new ImageIcon(AdminMainPage.class.getResource("/images/register.png")));
		menuBar.add(menu);
		
		JMenuItem menuItem_1 = new JMenuItem("新增");
		menuItem_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				AddStudent addStudent = new AddStudent();
				addStudent.setVisible(true);
				table.add(addStudent);
			}
		});
		menu.add(menuItem_1);
		
		JMenu menu_1 = new JMenu("维护学生信息");
		menu_1.setIcon(new ImageIcon(AdminMainPage.class.getResource("/images/用户.png")));
		menuBar.add(menu_1);
		
		JMenuItem mntmNewMenuItem = new JMenuItem("维护");
		mntmNewMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				UpdateStudent updateStudent = new UpdateStudent();
				updateStudent.setVisible(true);
				table.add(updateStudent);
			}
		});
		menu_1.add(mntmNewMenuItem);
		
		JMenu menu_2 = new JMenu("安全退出");
		menu_2.setIcon(new ImageIcon(AdminMainPage.class.getResource("/images/login.png")));
		menuBar.add(menu_2);
		
		JMenuItem menuItem = new JMenuItem("退出");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				exit();
			}
		});
		menu_2.add(menuItem);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		table = new JDesktopPane();
		table.setBackground(new Color(0, 128, 128));
		contentPane.add(table, BorderLayout.CENTER);
		
		// 窗口居中
		this.setLocationRelativeTo(null);
	}

	private void exit() {
		// TODO Auto-generated method stub
		dispose();
	}

}

3.4.3 Login

public class Login extends JFrame {

	private JPanel contentPane;
	private JTextField username;
	private JPasswordField password;
	private static Login frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frame = new Login();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Login() {
		setTitle("欢迎来到学生管理系统");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JLabel lblNewLabel = new JLabel("学生管理系统");
		lblNewLabel.setIcon(new ImageIcon(Login.class.getResource("/images/学生.png")));
		lblNewLabel.setFont(new Font("宋体", Font.BOLD, 20));

		JLabel label = new JLabel("\u8D26\u53F7\uFF1A");
		label.setIcon(new ImageIcon(Login.class.getResource("/images/user.png")));
		label.setFont(new Font("宋体", Font.PLAIN, 14));

		username = new JTextField();
		username.setColumns(10);

		JLabel label_1 = new JLabel("\u5BC6\u7801\uFF1A");
		label_1.setIcon(new ImageIcon(Login.class.getResource("/images/password.png")));
		label_1.setFont(new Font("宋体", Font.PLAIN, 14));

		password = new JPasswordField();

		JButton button = new JButton("\u767B\u5F55");
		button.setIcon(new ImageIcon(Login.class.getResource("/images/login.png")));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Login();
			}
		});

		JButton btnNewButton = new JButton("重置");
		btnNewButton.setIcon(new ImageIcon(Login.class.getResource("/images/reset.png")));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				reset();
			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING).addGroup(gl_contentPane
				.createSequentialGroup().addContainerGap(110, Short.MAX_VALUE)
				.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_contentPane.createSequentialGroup().addComponent(button).addGap(18)
								.addComponent(btnNewButton).addGap(
										120))
						.addGroup(gl_contentPane.createSequentialGroup().addGroup(gl_contentPane
								.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane
										.createParallelGroup(Alignment.TRAILING, false).addGroup(gl_contentPane
												.createSequentialGroup()
												.addComponent(label_1, GroupLayout.DEFAULT_SIZE,
														GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
												.addPreferredGap(ComponentPlacement.UNRELATED).addComponent(password,
														GroupLayout.PREFERRED_SIZE, 133, GroupLayout.PREFERRED_SIZE))
										.addGroup(gl_contentPane.createSequentialGroup().addComponent(label).addGap(10)
												.addComponent(username, GroupLayout.PREFERRED_SIZE, 133,
														GroupLayout.PREFERRED_SIZE)))
								.addComponent(lblNewLabel)).addGap(120)))));
		gl_contentPane
				.setVerticalGroup(
						gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_contentPane.createSequentialGroup().addGap(28).addComponent(lblNewLabel)
										.addGap(26)
										.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
												.addGroup(gl_contentPane.createSequentialGroup().addGap(2)
														.addComponent(label))
												.addComponent(username, GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
										.addGap(20)
										.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
												.addComponent(label_1, GroupLayout.PREFERRED_SIZE, 16,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(password, GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
										.addGap(18)
										.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
												.addComponent(btnNewButton).addComponent(button))
										.addContainerGap(26, Short.MAX_VALUE)));
		contentPane.setLayout(gl_contentPane);

		ButtonGroup group = new ButtonGroup();

		// 居中显示
		this.setLocationRelativeTo(null);
	}

	private void reset() {
		// TODO Auto-generated method stub
		this.username.setText("");
		this.password.setText("");
	}

	private void Login() {
		// TODO Auto-generated method stub
		String username = this.username.getText();
		String password = new String(this.password.getPassword());

		if (StringUtil.isNull(username)) {
			JOptionPane.showMessageDialog(null, "用户名不能为空!");
			return;
		}

		if (StringUtil.isNull(password)) {
			JOptionPane.showMessageDialog(null, "密码不能为空!");
			return;
		}

		AdminDao adminDao = new AdminDao();
		Map<String, String> map = adminDao.readAdmin();
		if (map.get(username) == null) {
			JOptionPane.showMessageDialog(null, "账号错误!");
			return;
		} else {
			if (!map.get(username).equals(password)) {
				JOptionPane.showMessageDialog(null, "密码错误!");
				return;
			} else {
				JOptionPane.showMessageDialog(null, "登入成功!");
				frame.setVisible(false);
				AdminMainPage adminMainPage = new AdminMainPage();
				adminMainPage.setVisible(true);
			}
		}
	}
}

3.4.4 UpdateStudent

public class UpdateStudent extends JInternalFrame {
	private JTextField findname;
	private JTable table;
	private JTextField name;
	private JTextField age;
	private JTextField address;
	private JTextField tel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UpdateStudent frame = new UpdateStudent();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public UpdateStudent() {
		setTitle("维护学生信息");
		setIconifiable(true);
		setClosable(true);
		setBounds(100, 100, 792, 492);
		
		JScrollPane scrollPane = new JScrollPane();
		
		JLabel label = new JLabel("学生姓名:");
		
		findname = new JTextField();
		findname.setColumns(10);
		
		JButton button = new JButton("搜索");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				findStudent();
			}
		});
		button.setIcon(new ImageIcon(UpdateStudent.class.getResource("/images/搜索.png")));
		
		JLabel label_1 = new JLabel("姓名:");
		
		name = new JTextField();
		name.setEditable(false);
		name.setColumns(10);
		
		JLabel label_2 = new JLabel("年龄:");
		
		age = new JTextField();
		age.setColumns(10);
		
		JLabel label_3 = new JLabel("地址:");
		
		address = new JTextField();
		address.setColumns(10);
		
		JLabel label_4 = new JLabel("电话:");
		
		tel = new JTextField();
		tel.setColumns(10);
		
		JButton button_1 = new JButton("修改");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				updateStudent();
			}
		});
		button_1.setIcon(new ImageIcon(UpdateStudent.class.getResource("/images/submit.png")));
		
		JButton button_2 = new JButton("删除");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				delStudent();
			}
		});
		button_2.setIcon(new ImageIcon(UpdateStudent.class.getResource("/images/删除(1).png")));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(109)
							.addComponent(label)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(findname, GroupLayout.PREFERRED_SIZE, 158, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(101)
							.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(label_1)
									.addGap(7)
									.addComponent(name, GroupLayout.PREFERRED_SIZE, 145, GroupLayout.PREFERRED_SIZE))
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(label_2)
									.addGap(8)
									.addComponent(age, GroupLayout.PREFERRED_SIZE, 146, GroupLayout.PREFERRED_SIZE))
								.addComponent(button_1))
							.addGap(85)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(button_2)
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
									.addGroup(groupLayout.createSequentialGroup()
										.addComponent(label_4)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(tel))
									.addGroup(groupLayout.createSequentialGroup()
										.addComponent(label_3)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(address, GroupLayout.PREFERRED_SIZE, 169, GroupLayout.PREFERRED_SIZE)))))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(71)
							.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 633, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap(72, Short.MAX_VALUE))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(47)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(label)
								.addComponent(findname, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(button))
							.addGap(122)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addGroup(groupLayout.createSequentialGroup()
									.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addGroup(groupLayout.createSequentialGroup()
											.addGap(45)
											.addComponent(label_1))
										.addGroup(groupLayout.createSequentialGroup()
											.addGap(43)
											.addComponent(name, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
									.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addGroup(groupLayout.createSequentialGroup()
											.addGap(36)
											.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
												.addComponent(age, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addComponent(label_4)
												.addComponent(tel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
										.addGroup(groupLayout.createSequentialGroup()
											.addGap(39)
											.addComponent(label_2))))
								.addGroup(groupLayout.createSequentialGroup()
									.addGap(44)
									.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
										.addComponent(label_3)
										.addComponent(address, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
							.addGap(62)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(button_1)
								.addComponent(button_2)))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(90)
							.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap(60, Short.MAX_VALUE))
		);
		
		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				pickRow();
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
			},
			new String[] {
				"\u59D3\u540D", "\u5E74\u9F84", "\u5730\u5740", "\u7535\u8BDD"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scrollPane.setViewportView(table);
		getContentPane().setLayout(groupLayout);
		
		filltable("");
	}

	private void updateStudent() {
		// TODO Auto-generated method stub
		String name = this.name.getText();
		String age = this.age.getText();
		String address = this.address.getText();
		String tel = this.tel.getText();
		
		if (StringUtil.isNull(name)) {
			JOptionPane.showMessageDialog(null, "姓名不能为空!");
			return;
		}
		if (StringUtil.isNull(age)) {
			JOptionPane.showMessageDialog(null, "年龄不能为空!");
			return;
		}
		if (StringUtil.isNull(address)) {
			JOptionPane.showMessageDialog(null, "地址不能为空!");
			return;
		}
		if (StringUtil.isNull(tel)) {
			JOptionPane.showMessageDialog(null, "电话不能为空!");
			return;
		}
		
		Student student = new Student(0, name, age, address, tel);
		StudentDao studentDao = new StudentDao();
		studentDao.delStudent(name);
		int num = studentDao.writeStudent(student);
		if (num != 0) {
			JOptionPane.showMessageDialog(null, "修改成功!");
			filltable("");
		}else {
			JOptionPane.showMessageDialog(null, "修改失败!");
		}
	}

	private void findStudent() {
		// TODO Auto-generated method stub
		String name = this.findname.getText();
		filltable(name);
	}

	private void delStudent() {
		// TODO Auto-generated method stub
		int result = JOptionPane.showConfirmDialog(null, "是否删除该学生?");
		if (result == 0) {
			String name = this.name.getText();
			StudentDao studentDao = new StudentDao();
			int num = studentDao.delStudent(name);
			if (num != 0) {
				JOptionPane.showMessageDialog(null, "删除成功!");
				filltable("");
				cleanPickRow();
			}else {
				JOptionPane.showMessageDialog(null, "删除失败!");
			}
		}
	}

	private void cleanPickRow() {
		// TODO Auto-generated method stub
		this.name.setText("");
		this.age.setText("");
		this.address.setText("");
		this.tel.setText("");
	}

	private void pickRow() {
		// TODO Auto-generated method stub
		int row = table.getSelectedRow();
		this.name.setText((String) table.getValueAt(row, 0));
		this.age.setText((String) table.getValueAt(row, 1));
		this.address.setText((String) table.getValueAt(row, 2));
		this.tel.setText((String) table.getValueAt(row, 3));
	}

	private void filltable(String name) {
		// TODO Auto-generated method stub
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		dtm.setRowCount(0);
		
		StudentDao studentDao = new StudentDao();
		ArrayList<Student> list = studentDao.findStudent(name);
		for (int i = 0; i < list.size(); i++) {
			Vector<Object> v = new Vector<>();
			v.add(list.get(i).getName());
			v.add(list.get(i).getAge());
			v.add(list.get(i).getAddress());
			v.add(list.get(i).getTel());

			dtm.addRow(v);
		}
	}
}

本文地址:https://blog.csdn.net/weixin_44197478/article/details/107364885

相关标签: JAVA基础 java