使用Java语言实现的一款日记软件。可以实现用户的注册、登录以及对日记的各种操作。
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class IndexGUI extends JFrame {
//自定义IndexGUI继承JFrame类
private JPanel contentPane; //声明面板
//创建JFrame的类对象声明
private static IndexGUI frame;
public static void main(String[] args) {
init();
}
public static void init() //初始化方法
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new IndexGUI(); //实例化frame
frame.setVisible(true); //设置窗体可见性
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public IndexGUI() {
setTitle("KnowYou"); //设置窗体标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭方式,点击窗体关闭按钮可关闭窗体
/*x - the new x-coordinate of this component
y - the new y-coordinate of this component
width - the new width of this component
height - the new height of this component */
setBounds(100, 100, 650, 400);
contentPane = new JPanel(); //实例化面板
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //设置面板大小,位置
setContentPane(contentPane); //frame添加面板
contentPane.setLayout(null); //面板设置布局为null,不可省略。否则页面布局将会杂乱。
JLabel lblNewLabel = new JLabel("Welcome to use KnowYou"); //标题
lblNewLabel.setBounds(132, 74, 386, 35);
lblNewLabel.setFont(new Font("黑体", Font.BOLD | Font.ITALIC, 30));
contentPane.add(lblNewLabel);
JButton login = new JButton("Login"); //登陆按钮
//登陆按钮鼠标事件,当鼠标被点击时调用
login.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
event_Login(); //登陆事件方法
}
});
//增加键盘事件
login.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
event_Login();//登陆事件方法
}
}
});
login.setBounds(65, 263, 124, 45);
contentPane.add(login);
JButton register = new JButton("Sign Up"); //注册按钮
//注册鼠标事件
register.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
event_register(); //注册事件方法
}
});
//注册按钮键盘事件
register.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
event_register();//注册事件方法
}
}
});
register.setBounds(489, 263, 109, 45);
contentPane.add(register);
}
//对登陆和注册事件进行私有方法封装
private void event_Login()
{
setVisible(false);
new LoginGUI().loginGUI();
}
private void event_register()
{
setVisible(false);
new RegisterGUI().registerGUI();
}
}
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import com.Joke.util.Register;
public class RegisterGUI extends JFrame{
private static final long serialVensionUID = 3250371445038102261L;
private JPanel contentPane;
private JTextField nametext;//name输入框
private JTextField IDtext;//ID输入框
private JTextField passwdtext;//密码输入框
public void registerGUI(){
EventQueue.invokeLater(new Runnable() {
public void run(){
try{
RegisterGUI frame = new RegisterGUI();
frame.setVisible(true);
}catch (Exception e){
e.printStackTrace();
}
}
}
);
}
public RegisterGUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,650,400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel namelabel = new JLabel("Please input user name");//设置提示姓名输入标签
namelabel.setBounds(102,91,151,23);
contentPane.add(namelabel);
JLabel IDlabel = new JLabel("please input user ID");//设置提示ID输入标签
IDlabel.setBounds(102,160,151,23);
contentPane.add(IDlabel);
JLabel passwdlaber = new JLabel("please input user password");//设置提示密码输入标签
passwdlaber.setBounds(102,224,163,23);
contentPane.add(passwdlaber);
nametext = new JTextField();//普通文本输入框
nametext.setBounds(271, 92, 92, 21);//设置位置及大小
contentPane.add(nametext);
nametext.setColumns(10); //设置长度
//ID
IDtext = new JTextField();
IDtext.setBounds(271, 161, 92, 21);
contentPane.add(IDtext);
IDtext.setColumns(8);
//密码
passwdtext = new JTextField();
passwdtext.setBounds(271, 225, 92, 21);
contentPane.add(passwdtext);
passwdtext.setColumns(10);
//注册按钮
JButton register = new JButton("Sign Up");
//注册按钮鼠标点击事件
register.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
String name = nametext.getText();//得到name
String ID = IDtext.getText();//得到ID
String passwd = passwdtext.getText();//得到密码
//如果检测ID返回为null
if (Register.checkID(ID) == null) {
//如果检测密码返回为null
if (Register.checkPasswd(passwd) == null) {
//注册信息,并且得到返回信息
String srt = Register.register(name, passwd, ID);
//提示框,注册成功
JOptionPane.showMessageDialog(contentPane,srt,"information", JOptionPane.PLAIN_MESSAGE);
//隐藏当前窗体
setVisible(false);
//返回首页
new IndexGUI().init();
} else {
//提示框,输出错误信息 JOptionPane.showMessageDialog(contentPane,Register.checkPasswd(passwd), "ERROR", JOptionPane.ERROR_MESSAGE);
}
} else {
//提示框,输出错误信息 JOptionPane.showMessageDialog(contentPane,Register.checkID(ID), "ERROR",
//JOptionPane.ERROR_MESSAGE();
}
}
});
register.setBounds(321, 305, 93, 23);
contentPane.add(register);
JButton back = new JButton("BACK"); //返回按钮
back.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
IndexGUI.init(); //创建首页
setVisible(false);//当前页面不可见
}
});
back.setBounds(531,305,93,23);
contentPane.add(back);
JLabel label = new JLabel("Welcome to use KnowYou"); //欢迎标题
label.setFont(new Font("黑体", Font.BOLD | Font.ITALIC, 30));
label.setBounds(143, 26, 374, 35);
contentPane.add(label);
JLabel lblNewLabel = new JLabel("(There are 1 to 8 numbers)");
lblNewLabel.setBounds(373, 164, 163, 15);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("(There are 6 to 15 numbers)");
lblNewLabel_1.setBounds(373, 228, 163, 15);
contentPane.add(lblNewLabel_1);
}
}
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import com.Joke.util.JDOM;
public class LoginGUI extends JFrame {
private static final long serialVersionUID = 4994949944841194839L;
private JPanel contentPane; //面板
private JTextField IDtxt; //ID输入框
private JLabel Passwdlabel;//密码标签
private JPasswordField passwordField;//密码输入框
private JButton login;//登陆按钮
private JButton back;//返回按钮
/**
* Launch the application.
* @return
*/
public void loginGUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginGUI frame = new LoginGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LoginGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel IDlabel = new JLabel("Please input ID");//ID标签
IDlabel.setBounds(68, 170, 91, 39);
contentPane.add(IDlabel);
IDtxt = new JTextField();
IDtxt.setBounds(206, 179, 126, 21);
contentPane.add(IDtxt);
IDtxt.setColumns(10);
Passwdlabel = new JLabel("Please input password");
Passwdlabel.setBounds(68, 219, 150, 50);
contentPane.add(Passwdlabel);
passwordField = new JPasswordField();
passwordField.setBounds(206, 234, 126, 21);
contentPane.add(passwordField);
login = new JButton("login");
//鼠标事件
login.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
event_login();//登陆事件方法
}
});
//键盘事件
login.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)//当键盘按下enter时调用
{
event_login();//登陆事件方法
}
}
});
login.setBounds(239, 310, 93, 23);
contentPane.add(login);
//返回按钮
back = new JButton("BACK");
back.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
IndexGUI.init();
setVisible(false);
}
});
back.setBounds(507, 310, 93, 23);
contentPane.add(back);
//标题
JLabel label = new JLabel("Welcome to use KnowYou");
label.setFont(new Font("黑体", Font.BOLD | Font.ITALIC, 30));
label.setBounds(142, 54, 386, 35);
contentPane.add(label);
}
//封装登陆事件
private void event_login()
{
String id=IDtxt.getText();
String passwd=new String(passwordField.getPassword());
String flag=JDOM.read(id, passwd);
if(flag.contains("Successful landing"))
{
//拆分信息
String[] bufs=flag.split("/");
String name=bufs[1];
//提示框,打印登陆成功
JOptionPane.showMessageDialog(contentPane, "Welcome:"+name,"Welcome",JOptionPane.PLAIN_MESSAGE);
UsersGUI.init(name);
setVisible(false);
}
else
{
//提示框,错误信息 JOptionPane.showMessageDialog(contentPane,flag,"ERROR",JOptionPane.ERROR_MESSAGE);
}
}
}
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import com.Joke.util.Diary;
import javax.swing.filechooser.FileNameExtensionFilter;
public class UsersGUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
//文件选择组建,用于用户阅读日记和删除日记时选择文件。
private JFileChooser chooser;
/*每个注册用户所记录的日记都位于自己的文件夹下,pathname用于保存用户的文件夹路径*/
private static String pathname;
public static void init(String path) { //初始化方法
pathname = path;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UsersGUI frame = new UsersGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UsersGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("KonwYou");
tabbedPane.setBounds(0, 0, 574, 67);
contentPane.add(tabbedPane);
final JPanel panel = new JPanel();
tabbedPane.addTab("Management Journal", null, panel, null);
chooser = new JFileChooser(".\\"+pathname);//初始化JFileChooser,并设置默认目录为用户目录
FileNameExtensionFilter filter=new FileNameExtensionFilter("Allowed","ky");//文件选择器,只允许选择.ky文件
chooser.setFileFilter(filter);//为文件设置选择器
JButton readButton = new JButton("Read the diary");
readButton.addMouseListener(new MouseAdapter() {
@Override
//阅读按钮鼠标事件,当用户点击时,将会创建一个新的内部窗体
public void mouseClicked(MouseEvent e) {
int value = chooser.showOpenDialog(panel);//判断用户是否选择了文件
//内部窗体
JInternalFrame internalFrame_Read = new JInternalFrame("Read the diary", false, true, false, false);
internalFrame_Read.setBounds(0, 77, 584, 275);
contentPane.add(internalFrame_Read);
internalFrame_Read.getContentPane().setLayout(null);
JTextPane txtDiary = new JTextPane();
txtDiary.setBounds(0, 0, 568, 246);
internalFrame_Read.getContentPane().add(txtDiary);
//JTextPane没有append方法,所以使用Document来不断插入文本
javax.swing.text.Document doc=txtDiary.getDocument();
txtDiary.setBackground(Color.GREEN);//背景颜色为绿色
txtDiary.setEditable(false);//设置为不可编辑
//当value的值和JFileChooser.APPROVE_OPTION相等时,证明用户选择了文件
if (value == JFileChooser.APPROVE_OPTION) {
//得到用户选择的文件
File file = chooser.getSelectedFile();
if(file.exists()) //如果文件存在
{
//Diary.read()方法读取日记;
//该方法将会在以后的课程中完成
Diary.read(file, doc);
internalFrame_Read.setVisible(true);
}
}
}
});
panel.add(readButton);
JButton addButton = new JButton("Create a diary");//新建按钮
addButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//创建新建日记内部窗体
final JInternalFrame internalFrame_Write = new JInternalFrame("Create a diary",false, true, false, false);
internalFrame_Write.setBounds(0, 77, 584, 275);
contentPane.add(internalFrame_Write);
internalFrame_Write.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(76, 0, 492, 21);
internalFrame_Write.getContentPane().add(textField);
textField.setColumns(10);
JLabel label = new JLabel("Title");
label.setFont(new Font("楷体", Font.PLAIN, 12));
label.setBounds(46, 3, 52, 15);
internalFrame_Write.getContentPane().add(label);
//日记编辑区
final JEditorPane editorPane = new JEditorPane();
editorPane.setBounds(0, 31, 568, 179);
internalFrame_Write.getContentPane().add(editorPane);
JButton save = new JButton("SAVE");//保存按钮
save.setBounds(465, 213, 93, 23);
save.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//获取标题
String title = textField.getText();
//获取内容
String txt = editorPane.getText();
//调用Diary.addDiary()方法建立日记
//该方法将会在以后的课程中完成
Diary.addDiary(pathname, title, txt);
//日记建立完成后隐藏当前窗口
internalFrame_Write.setVisible(false);
}
});
internalFrame_Write.getContentPane().add(save);
internalFrame_Write.setVisible(true);
}
});
panel.add(addButton);
//删除按钮
JButton delButton = new JButton("Delete");
delButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File file=null;
int value=chooser.showOpenDialog(panel);
if(value==JFileChooser.APPROVE_OPTION)
{
file=chooser.getSelectedFile();
//删除确认框,用于确定用户是否确定删除
int x= JOptionPane.showConfirmDialog(panel,"Confirm delete?","Please confirm",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
if(file.exists())
{
//当用户选择了OK时,调用删除方法
if(x==JOptionPane.OK_OPTION)
{
file.delete();
//打印删除成功提示信息
JOptionPane.showMessageDialog(panel, "Delete Success!","information", JOptionPane.PLAIN_MESSAGE);
}
}
}
}
});
panel.add(delButton);
//返回按钮
JButton back = new JButton("BACK");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IndexGUI.init();
setVisible(false);
}
});
panel.add(back);
}
}
一.用户类
package com.Joke.entity;
/*这就是一个封装类,封装了用户的数据,使用者只能看到公共方法,而看不到数据,通过set方法和get方法来访问封装类的数据*/
/*用户名、ID、密码*/
public class User {
private String ID ; //登录ID
private String name ;//姓名
private String passwd; //密码
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
XML文件
一、(1)开始学习JDOM
(2)下载JDOM
涉及到的基础知识:
I/O 、 集合 、 xml数据封装
代码:
package com.Joke.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class JDOM {
//注册用户信息
public static String write(String n, String p, String id) {
// TODO Auto-generated method stub
//UserInfo.xml文档的路径
String path = "C:/Users/Administrator/Desktop/UserInfo.xml";
//将xml文档封装成file
File file = new File(path);
//使用默认的sax解析器
SAXBuilder saxBuilder = new SAXBuilder();
Document doc; //声明document文档
try {
doc = saxBuilder.build(file);
//元素对应到xml文档中就是标签
Element root = doc.getRootElement(); //得到根元素
Element user = new Element("User"); //建立User元素
Element name = new Element("name");//建立name元素
Element passwd = new Element("passwd");//建立passwd元素
/*首先检测xml文档中是否已经存在了ID号相同的用户,如果不存在才可以继续注册*/
if (checkID(id, root)) {
//将ID设置为user的属性
user.setAttribute(new Attribute("id", id));
//设置姓名和密码
name.setText(n);
passwd.setText(p);
//将name,passwd元素添加到user元素下
user.addContent(name);
user.addContent(passwd);
//将user元素添加到根元素下
root.addContent(user);
//输出xml文档
XMLOutputter out = new XMLOutputter();
out.output(doc, new FileOutputStream(file));
return "Successful registration";//返回注册成功
} else
//返回ID存在信息,重新输入ID
return "ID already exists, please input again";
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "ERROR";//未知错误
}
public static boolean checkID(String id, Element root) {
// 检测ID是否存在
boolean flag = true;
@SuppressWarnings("unchecked")
//得到User标签的所有子元素,并加入到map集合中
List list = root.getChildren("User");
//迭代检测是否存在ID
Iterator it = list.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
if (e.getAttributeValue("id").equals(id)) {
flag = false;
}
}
return flag;
}
//读取xml文档用于登录
public static String read(String id, String passwd) {
String path = "C:/Users/Administrator/Desktop/UserInfo.xml";
File file = new File(path);
SAXBuilder saxBuilder = new SAXBuilder();
try {
Document doc = saxBuilder.build(file);
Element root = doc.getRootElement();
//取出用户密码和姓名
String info = getPasswd(root).get(id);
if (info == null) {
return "User does not exist!!";
}
String[] buf = info.split("/");
if (buf[0].equals(passwd)) {
return "Successful landing/" + buf[1];
}
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Wrong password!!";
}
@SuppressWarnings("unchecked")
/*将用户的密码和姓名添加到map集合中*/
private static Map getPasswd(Element root) {
Map map = new TreeMap();//存贮用户信息
List list = new ArrayList();
//得到User标签的所有子元素信息
list = root.getChildren("User");
Iterator it = list.iterator();
while (it.hasNext()) {
Element e = it.next();
String id = e.getAttributeValue("id");
String passwd = e.getChildText("passwd");
String name = e.getChildText("name");
map.put(id, getInfo(passwd, name));
}
return map;
}
//处理用户密码和信息
private static String getInfo(String passwd, String name) {
return passwd + "/" + name;
}
}
涉及到的知识:
正则表达式
代码:
package com.Joke.util;
import com.Joke.entity.User;
public class Register {
static User user = new User();
public static String checkName(String name) {
user.setName(name);
return null;
}
public static String checkID(String ID) {
if (ID.matches("\\d{1,8}")) {
user.setID(ID);
return null;
} else
return "ID not conform to the rules";
}
public static String checkPasswd(String passwd) {
if (passwd.matches("\\d{6,15}")) {
user.setPasswd(passwd);
return null;
} else
return "Password not conform to the rules";
}
//如果以上验证都没有错误信息返回,则执行写入用户信息
public static String register(String name,String passwd,String ID) {
user.setName(name);
user.setPasswd(passwd);
user.setID(ID);
return (JDOM.write(user.getName(), user.getPasswd(),
user.getID()));
}
}
一、 本节目标
实现将用户的记录的日记写入到本地磁盘中
二、代码
package com.Joke.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.text.Document;
public class Diary {
public static void addDiary(String pathname, String title, String txt) {
// pathname是以用户名命名的文件夹
File dirfile = new File(pathname);
BufferedWriter bufw = null;
// 建立文件夹
dirfile.mkdirs();
// 建立日记文件,后缀为.kz
File file = new File(dirfile, title + ".ky");
try {
//写入文件
bufw = new BufferedWriter(new FileWriter(file, true));
bufw.write(txt);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bufw != null) {
try {
bufw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void read(File file, Document doc) {
// 创建读取流,读取文件内容,并将读到的内容添加到日记显示区
try (BufferedReader bufr = new BufferedReader(new FileReader(file));) {
String txt = null;
// 获取换行符,因为Linux和Windows下的换行符是不一样的。这样可以增强跨平台性
String line = System.getProperty("line.separator");
while ((txt = bufr.readLine()) != null) {
doc.insertString(doc.getLength(), txt + line, null);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}