Java案例7-4升级版日记本:多用户、分类、标签、搜索、导出、打印、评论、分享
Java案例7-4升级版日记本:多用户、分类、标签、搜索、导出、打印、评论、分享
升级版日记本要求实现以下功能:
-
支持多用户登录和注册,每个用户有自己的日记本。
-
支持对日记进行分类和标签。
-
支持对日记进行搜索和排序,可以按照时间、标题、分类、标签等进行排序。
-
支持导出日记为文本文件或者打印出来。
-
支持对已有日记进行修改和删除。
-
支持设置日记本的密码保护。
-
支持对日记的评论和回复。
-
支持对日记进行分享到社交网络。
实现思路:
-
使用Java Swing进行界面设计,使用MySQL数据库进行数据存储。
-
用户登录和注册使用JDBC连接数据库进行验证和保存数据。
-
日记的分类和标签使用JComboBox进行选择和编辑,使用JTextField进行输入和保存。
-
日记的搜索和排序使用JTable显示日记数据,使用JTextField进行搜索和JComboBox进行排序,使用JFileChooser进行导出和打印。
-
日记的修改和删除使用JOptionPane进行提示和确认,使用JTextField进行修改和JTable进行删除。
-
日记本的密码保护使用JPasswordField进行密码输入和验证。
-
日记的评论和回复使用JTextArea进行输入和显示,使用JButton进行保存和回复。
-
日记的分享使用JOptionPane进行提示和选择,使用JFileChooser进行选择和保存。
代码实现:
1. 用户登录和注册
//登录界面
JLabel nameLabel = new JLabel('用户名:');
JTextField nameField = new JTextField(10);
JLabel passLabel = new JLabel('密码:');
JPasswordField passField = new JPasswordField(10);
JButton loginButton = new JButton('登录');
JButton registerButton = new JButton('注册');
//登录按钮
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String pass = String.valueOf(passField.getPassword());
if (name.equals('') || pass.equals('')) {
JOptionPane.showMessageDialog(null, '用户名或密码不能为空!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
boolean flag = checkUser(name, pass);
if (flag) {
JOptionPane.showMessageDialog(null, '登录成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
//打开日记界面并关闭登录界面
new DiaryFrame(name).setVisible(true);
LoginFrame.this.dispose();
} else {
JOptionPane.showMessageDialog(null, '用户名或密码错误!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
});
//注册按钮
registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String pass = String.valueOf(passField.getPassword());
if (name.equals('') || pass.equals('')) {
JOptionPane.showMessageDialog(null, '用户名或密码不能为空!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
boolean flag = addUser(name, pass);
if (flag) {
JOptionPane.showMessageDialog(null, '注册成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, '用户名已存在!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
});
//登录验证
public boolean checkUser(String name, String pass) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'select * from user where name=? and pass=?';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
flag = true;
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
//注册保存
public boolean addUser(String name, String pass) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'insert into user(name, pass) values(?,?)';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, pass);
int count = pstmt.executeUpdate();
if (count > 0) {
flag = true;
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
2. 日记的分类和标签
//分类下拉框
String[] types = {'旅行', '工作', '生活', '学习'};
JComboBox<String> typeBox = new JComboBox<>(types);
typeBox.setSelectedIndex(0);
typeBox.setEditable(true);
typeBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String type = (String) typeBox.getSelectedItem();
if (!Arrays.asList(types).contains(type)) {
typeBox.addItem(type);
}
}
});
//标签输入框
JLabel tagLabel = new JLabel('标签:');
JTextField tagField = new JTextField(20);
//保存按钮
JButton saveButton = new JButton('保存');
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String title = titleField.getText();
String content = contentArea.getText();
String type = (String) typeBox.getSelectedItem();
String tag = tagField.getText();
if (title.equals('') || content.equals('')) {
JOptionPane.showMessageDialog(null, '标题或内容不能为空!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
boolean flag = addDiary(title, content, type, tag);
if (flag) {
JOptionPane.showMessageDialog(null, '保存成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, '保存失败!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
});
//保存日记
public boolean addDiary(String title, String content, String type, String tag) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'insert into diary(title, content, type, tag) values(?,?,?,?)';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, content);
pstmt.setString(3, type);
pstmt.setString(4, tag);
int count = pstmt.executeUpdate();
if (count > 0) {
flag = true;
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
3. 日记的搜索和排序
//搜索框
JLabel searchLabel = new JLabel('搜索:');
JTextField searchField = new JTextField(20);
searchField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
searchDiary();
}
public void removeUpdate(DocumentEvent e) {
searchDiary();
}
public void changedUpdate(DocumentEvent e) {
searchDiary();
}
});
//排序下拉框
String[] sorts = {'时间', '标题', '分类', '标签'};
JComboBox<String> sortBox = new JComboBox<>(sorts);
sortBox.setSelectedIndex(0);
sortBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sortDiary();
}
});
//搜索日记
public void searchDiary() {
String keyword = searchField.getText();
String sql = 'select * from diary where title like '%' + keyword + '%' or content like '%' + keyword + '%' or type like '%' + keyword + '%' or tag like '%' + keyword + '%'';
showDiary(sql);
}
//排序日记
public void sortDiary() {
String sort = (String) sortBox.getSelectedItem();
String sql = '';
if (sort.equals('时间')) {
sql = 'select * from diary order by time desc';
} else if (sort.equals('标题')) {
sql = 'select * from diary order by title asc';
} else if (sort.equals('分类')) {
sql = 'select * from diary order by type asc';
} else if (sort.equals('标签')) {
sql = 'select * from diary order by tag asc';
}
showDiary(sql);
}
//显示日记
public void showDiary(String sql) {
DefaultTableModel model = new DefaultTableModel();
model.addColumn('ID');
model.addColumn('时间');
model.addColumn('标题');
model.addColumn('分类');
model.addColumn('标签');
model.addColumn('内容');
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Object[] row = new Object[6];
row[0] = rs.getInt('id');
row[1] = rs.getString('time');
row[2] = rs.getString('title');
row[3] = rs.getString('type');
row[4] = rs.getString('tag');
row[5] = rs.getString('content');
model.addRow(row);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
table.setModel(model);
}
4. 导出日记和打印日记
//导出按钮
JButton exportButton = new JButton('导出');
exportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogTitle('导出日记');
chooser.setApproveButtonText('导出');
chooser.setFileFilter(new FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith('.txt') || f.isDirectory();
}
public String getDescription() {
return '文本文件(*.txt)';
}
});
int result = chooser.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (!file.getName().toLowerCase().endsWith('.txt')) {
file = new File(file.getAbsolutePath() + '.txt');
}
if (file.exists()) {
int option = JOptionPane.showConfirmDialog(null, '文件已存在,确定要覆盖吗?', '提示', JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (option == JOptionPane.NO_OPTION) {
return;
}
}
boolean flag = exportDiary(file);
if (flag) {
JOptionPane.showMessageDialog(null, '导出成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, '导出失败!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
});
//打印按钮
JButton printButton = new JButton('打印');
printButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
table.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
});
//导出日记
public boolean exportDiary(File file) {
boolean flag = false;
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery('select * from diary');
FileWriter writer = new FileWriter(file);
while (rs.next()) {
String id = rs.getString('id');
String time = rs.getString('time');
String title = rs.getString('title');
String type = rs.getString('type');
String tag = rs.getString('tag');
String content = rs.getString('content');
writer.write(id + ' ' + time + ' ' + title + ' ' + type + ' ' + tag + ' ' + content + '\n');
}
writer.close();
rs.close();
stmt.close();
conn.close();
flag = true;
} catch (SQLException | IOException e) {
e.printStackTrace();
}
return flag;
}
5. 日记的修改和删除
//修改按钮
JButton editButton = new JButton('修改');
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(null, '请选择要修改的日记!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
int id = (int) table.getValueAt(row, 0);
String title = (String) table.getValueAt(row, 2);
String content = (String) table.getValueAt(row, 5);
String type = (String) table.getValueAt(row, 3);
String tag = (String) table.getValueAt(row, 4);
DiaryDialog dialog = new DiaryDialog(DiaryFrame.this, '修改日记', true, id, title, content, type, tag);
dialog.setVisible(true);
}
}
});
//删除按钮
JButton deleteButton = new JButton('删除');
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(null, '请选择要删除的日记!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
int option = JOptionPane.showConfirmDialog(null, '确定要删除吗?', '提示', JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
int id = (int) table.getValueAt(row, 0);
boolean flag = deleteDiary(id);
if (flag) {
JOptionPane.showMessageDialog(null, '删除成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, '删除失败!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
//修改日记对话框
public class DiaryDialog extends JDialog {
private int id;
private JTextField titleField;
private JTextArea contentArea;
private JComboBox<String> typeBox;
private JTextField tagField;
public DiaryDialog(Frame owner, String title, boolean modal, int id, String titleText, String contentText, String typeText, String tagText) {
super(owner, title, modal);
this.id = id;
JLabel titleLabel = new JLabel('标题:');
titleField = new JTextField(20);
titleField.setText(titleText);
JLabel contentLabel = new JLabel('内容:');
contentArea = new JTextArea(20, 40);
JScrollPane contentPane = new JScrollPane(contentArea);
contentArea.setText(contentText);
JLabel typeLabel = new JLabel('分类:');
String[] types = {'旅行', '工作', '生活', '学习'};
typeBox = new JComboBox<>(types);
typeBox.setSelectedItem(typeText);
typeBox.setEditable(true);
typeBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String type = (String) typeBox.getSelectedItem();
if (!Arrays.asList(types).contains(type)) {
typeBox.addItem(type);
}
}
});
JLabel tagLabel = new JLabel('标签:');
tagField = new JTextField(20);
tagField.setText(tagText);
JButton saveButton = new JButton('保存');
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String title = titleField.getText();
String content = contentArea.getText();
String type = (String) typeBox.getSelectedItem();
String tag = tagField.getText();
if (title.equals('') || content.equals('')) {
JOptionPane.showMessageDialog(null, '标题或内容不能为空!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
boolean flag = updateDiary(id, title, content, type, tag);
if (flag) {
JOptionPane.showMessageDialog(null, '保存成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
DiaryDialog.this.dispose();
showDiary('select * from diary');
} else {
JOptionPane.showMessageDialog(null, '保存失败!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
});
JPanel panel = new JPanel();
panel.add(titleLabel);
panel.add(titleField);
panel.add(contentLabel);
panel.add(contentPane);
panel.add(typeLabel);
panel.add(typeBox);
panel.add(tagLabel);
panel.add(tagField);
panel.add(saveButton);
this.add(panel);
this.pack();
this.setLocationRelativeTo(null);
}
}
//修改日记
public boolean updateDiary(int id, String title, String content, String type, String tag) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'update diary set title=?, content=?, type=?, tag=? where id=?';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, content);
pstmt.setString(3, type);
pstmt.setString(4, tag);
pstmt.setInt(5, id);
int count = pstmt.executeUpdate();
if (count > 0) {
flag = true;
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
//删除日记
public boolean deleteDiary(int id) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'delete from diary where id=?';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
int count = pstmt.executeUpdate();
if (count > 0) {
flag = true;
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
6. 日记本的密码保护
//密码输入框
JLabel passLabel = new JLabel('密码:');
JPasswordField passField = new JPasswordField(10);
JButton passButton = new JButton('确定');
passButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String pass = String.valueOf(passField.getPassword());
if (pass.equals('')) {
JOptionPane.showMessageDialog(null, '密码不能为空!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
boolean flag = checkPassword(pass);
if (flag) {
JOptionPane.showMessageDialog(null, '密码正确!', '提示', JOptionPane.INFORMATION_MESSAGE);
passDialog.dispose();
} else {
JOptionPane.showMessageDialog(null, '密码错误!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
});
//检查密码
public boolean checkPassword(String pass) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'select * from user where name=? and pass=?';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user);
pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
flag = true;
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
7. 日记的评论和回复
//评论输入框
JLabel commentLabel = new JLabel('评论:');
JTextArea commentArea = new JTextArea(5, 20);
JScrollPane commentPane = new JScrollPane(commentArea);
JButton commentButton = new JButton('评论');
commentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(null, '请选择要评论的日记!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
int id = (int) table.getValueAt(row, 0);
String content = commentArea.getText();
if (content.equals('')) {
JOptionPane.showMessageDialog(null, '评论内容不能为空!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
boolean flag = addComment(id, content);
if (flag) {
JOptionPane.showMessageDialog(null, '评论成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
commentArea.setText('');
showComments(id);
} else {
JOptionPane.showMessageDialog(null, '评论失败!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
//回复按钮
JButton replyButton = new JButton('回复');
replyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = commentTable.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(null, '请选择要回复的评论!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
int id = (int) commentTable.getValueAt(row, 0);
String content = commentArea.getText();
if (content.equals('')) {
JOptionPane.showMessageDialog(null, '回复内容不能为空!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
boolean flag = addReply(id, content);
if (flag) {
JOptionPane.showMessageDialog(null, '回复成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
commentArea.setText('');
showComments(diaryId);
} else {
JOptionPane.showMessageDialog(null, '回复失败!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
//保存评论
public boolean addComment(int diaryId, String content) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'insert into comment(diaryId, content) values(?,?)';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, diaryId);
pstmt.setString(2, content);
int count = pstmt.executeUpdate();
if (count > 0) {
flag = true;
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
//保存回复
public boolean addReply(int commentId, String content) {
boolean flag = false;
try {
Connection conn = getConnection();
String sql = 'insert into reply(commentId, content) values(?,?)';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, commentId);
pstmt.setString(2, content);
int count = pstmt.executeUpdate();
if (count > 0) {
flag = true;
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
//显示评论
public void showComments(int diaryId) {
DefaultTableModel model = new DefaultTableModel();
model.addColumn('ID');
model.addColumn('评论内容');
model.addColumn('回复');
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery('select * from comment where diaryId=' + diaryId);
while (rs.next()) {
Object[] row = new Object[3];
row[0] = rs.getInt('id');
row[1] = rs.getString('content');
row[2] = getReplies(rs.getInt('id'));
model.addRow(row);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
commentTable.setModel(model);
}
//获取回复
private String getReplies(int commentId) {
StringBuilder replies = new StringBuilder();
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery('select * from reply where commentId=' + commentId);
while (rs.next()) {
replies.append(rs.getString('content')).append('\n');
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return replies.toString();
}
8. 日记的分享
//分享按钮
JButton shareButton = new JButton('分享');
shareButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(null, '请选择要分享的日记!', '提示', JOptionPane.WARNING_MESSAGE);
} else {
int id = (int) table.getValueAt(row, 0);
String title = (String) table.getValueAt(row, 2);
String content = (String) table.getValueAt(row, 5);
String type = (String) table.getValueAt(row, 3);
String tag = (String) table.getValueAt(row, 4);
String shareContent = '标题:' + title + '\n' + '内容:' + content + '\n' + '分类:' + type + '\n' + '标签:' + tag;
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogTitle('分享日记');
chooser.setApproveButtonText('分享');
chooser.setFileFilter(new FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith('.txt') || f.isDirectory();
}
public String getDescription() {
return '文本文件(*.txt)';
}
});
int result = chooser.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (!file.getName().toLowerCase().endsWith('.txt')) {
file = new File(file.getAbsolutePath() + '.txt');
}
if (file.exists()) {
int option = JOptionPane.showConfirmDialog(null, '文件已存在,确定要覆盖吗?', '提示', JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (option == JOptionPane.NO_OPTION) {
return;
}
}
boolean flag = writeShareContent(file, shareContent);
if (flag) {
JOptionPane.showMessageDialog(null, '分享成功!', '提示', JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, '分享失败!', '提示', JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
//写入分享内容
private boolean writeShareContent(File file, String content) {
boolean flag = false;
try {
FileWriter writer = new FileWriter(file);
writer.write(content);
writer.close();
flag = true;
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
总结
本案例使用Java Swing、JDBC、MySQL数据库实现了一个功能丰富的日记本应用程序,涵盖了用户管理、日记管理、搜索排序、导出打印、评论回复、分享等功能。开发者可以根据自己的需求进行扩展和修改,以实现更强大的功能。
注意:本案例代码仅供参考,需要根据实际情况进行调整和完善。
原文地址: https://www.cveoy.top/t/topic/mwTY 著作权归作者所有。请勿转载和采集!