Java实验四(下):基于文件的小型通讯录

实验目的

能够掌握常用组件操作及文本处理,为下一步数据库做准备

实验内容

设计一个小型通讯录

实验要求

1、使用前需先登录,登录成功后方可使用,登录用户名和密码保存在一个文本文件中
2、可添加好友,好友信息包括:姓名(文本框)、性别(单选框)、年龄(滑动条)、爱好(复选框)、现居住城市(下拉列表)
3、点击保存,将信息保存到文件(可以将多人信息保存到一个文件中,也可以将每个人的信息保存到独立文件中)
4、输入姓名,点击查询,将给好友信息进行显示
5、输入姓名,点击删除,将该好友删除
6、建议一个好友一个文件,文件名的命名可以是 好友名.txt,方便后续操作

实验代码

package experiment_four;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;

class LoginFrame extends Frame {
    private static final long serialVersionUID = 1L;
    private JFrame jFrame = new JFrame("登录窗口");
    private Container c = jFrame.getContentPane();
    private JLabel a1 = new JLabel("用户名");
    // 默认账号
    private JTextField username = new JTextField();
    private JLabel a2 = new JLabel("密   码");
    // 默认密码
    private JPasswordField password = new JPasswordField();
    private JButton okbtn = new JButton("登录");

    public LoginFrame() {
        // 设置窗体的位置及大小
        jFrame.setBounds(600, 200, 300, 220);
        // 设置一层相当于桌布的东西
        c.setLayout(new BorderLayout());// 布局管理器
        // 设置按下右上角X号后关闭
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 初始化--往窗体里放其他控件
        jFrame.setLocationRelativeTo(null);// 窗
        // 标题部分
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(new FlowLayout());
        titlePanel.add(new JLabel("通讯录系统"));
        c.add(titlePanel, "North");
        // 输入部分-
        JPanel fieldPanel = new JPanel();
        fieldPanel.setLayout(null);
        a1.setBounds(50, 20, 50, 20);
        a2.setBounds(50, 60, 50, 20);
        fieldPanel.add(a1);
        fieldPanel.add(a2);
        username.setBounds(110, 20, 120, 20);
        password.setBounds(110, 60, 120, 20);
        fieldPanel.add(username);
        fieldPanel.add(password);
        c.add(fieldPanel, "Center");
        // 按钮部分
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(okbtn);
        c.add(buttonPanel, "South");
        // 设置窗体可见
        jFrame.setVisible(true);
        // 确认按下去获取
        okbtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String uname = username.getText();
                    String pwd = String.valueOf(password.getPassword());
                    boolean flag = UserDao.auth(uname, pwd);
                    if (flag) {
                        jFrame.setVisible(false);
                        JOptionPane.showMessageDialog(null, "恭喜您,登录成功!");
                        MainMenuFrame m = new MainMenuFrame();
                        //m.setVisible(true);
                        // 窗口居中
                       // m.setLocationRelativeTo(null);
                    } else {
                        JOptionPane.showMessageDialog(null, "登录失败,账号或密码错误");
                    }
                } catch (HeadlessException e1) {
                    username.setText("");
                    password.setText("");
                    JOptionPane.showMessageDialog(null, "登录失败");
                }

            }
        });
    }
}

class UserDao {
    private static final String fileName = "./user.txt";
    /**
     * 登录验证
     */
    public static boolean auth(String username, String password) {
        try {
            File file = new File(fileName);
            if(!file.exists()||file.isDirectory()) //判断文件是否存在
            	file.createNewFile();
            BufferedReader br=new BufferedReader(new FileReader(file)); //创建读入缓冲流,按行读入
            String temp=null;    
            temp=br.readLine();   //先读取一行
            while(temp!=null){
            	String sbstring = temp.toString();   //转化为string
            	if(username.equals(sbstring)) {
            		temp=br.readLine(); 
            		sbstring = temp.toString(); 
            		if(password.equals(sbstring)) {
            			return true;
            		}
            	}else {
            		return false;
            	}
            }
            return false;
        } catch (IOException e) {
            return false;
        }
    }
}


class MainMenuFrame extends JFrame implements ActionListener{
	/*
	 * 登陆成功后主界面
	 */
		private JFrame mainmenu;
		//private JTextArea text;
		private JMenuBar menuBar1;
		
		public MainMenuFrame() {
			mainmenu();
		}
		public void mainmenu() {
			mainmenu = new JFrame("通讯录系统");
			setLocationRelativeTo(null);// 将容器显示在屏幕中央
			mainmenu.setSize(750, 650);

			//mainmenu.getContentPane().add(new JScrollPane(text));

			JPanel jContentPane = new JPanel();
			jContentPane.setLayout(null);
			
			// 添加学生按钮
			JButton jButtonAdd = new JButton();
			jButtonAdd.setBounds(new Rectangle(320, 100, 100, 52));
			jButtonAdd.setText("添加学生");
			
			// 查询学生按钮
			JButton jButtonSelect = new JButton();
			jButtonSelect.setBounds(new Rectangle(320, 200, 100, 52));
			jButtonSelect.setText("查询学生");
			
			//删除学生按钮
			JButton jButtonDelete = new JButton();
			jButtonDelete.setBounds(new Rectangle(320, 300, 100, 52));
			jButtonDelete.setText("删除学生");
			
			// 退出系统按钮
			JButton jButtonExit = new JButton();
			jButtonExit.setBounds(new Rectangle(320, 400, 100, 52));
			jButtonExit.setText("退出系统");
			
			jContentPane.add(jButtonAdd, null);
			jContentPane.add(jButtonSelect, null);
			jContentPane.add(jButtonDelete, null);
			jContentPane.add(jButtonExit, null);
					
			// 添加Label到Frame
			mainmenu.getContentPane().add(jContentPane);
			// 标题栏
			menuBar1 = new JMenuBar();

			
			// 添加学生
			jButtonAdd.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					AddStudent addStudent = new AddStudent();
					
					System.out.println("------添加学生-----");
					
				}
			});
			// 查询学生
			jButtonSelect.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					SelectStudent selectStudent = new SelectStudent();
					System.out.println("------查询学生-----");
								
				}
			});
			//删除学生
			jButtonDelete.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					DeleteStudent deleteStudent = new DeleteStudent();
				}
				
			});
			// 退出系统
			jButtonExit.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					System.out.println("------退出系统-----");
					System.exit(1);
				}
			});

			// 关闭窗口监控
			mainmenu.addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent arg0) {
					System.exit(1);
				}
			});

			mainmenu.setJMenuBar(menuBar1);
			mainmenu.setVisible(true);
			mainmenu.setLocation(250, 50);
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
		}
}

class AddStudent extends JFrame{
		JTextField text,text2;
		JButton button;
		JCheckBox checkBox1,checkBox2,checkBox3;
		JRadioButton radio1,radio2;
		ButtonGroup group;
		JComboBox<String> comBox;
		//JTextArea area;
		public AddStudent(){
			init();
			setVisible(true);
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			setBounds(100,100,300,260);
			setTitle("添加页面");

		}
		void init() {
			// TODO Auto-generated method stub
			setLayout(new FlowLayout());
			JLabel label = new JLabel("姓名:");
			add(label);
			text = new JTextField(10);
			add(text);
			
			
			radio1 = new JRadioButton("男");//单选按钮
			radio2 = new JRadioButton("女");
			group = new ButtonGroup();
			group.add(radio1);
			group.add(radio2);
			add(radio1);
			add(radio2);
			
			checkBox1 = new JCheckBox("喜欢音乐");
			checkBox2 = new JCheckBox("喜欢旅游");
			checkBox3 = new JCheckBox("喜欢篮球");
			add(checkBox1);
			add(checkBox2);
			add(checkBox3);
			
			comBox = new JComboBox();//下拉列表
			comBox.addItem("居住城市");
			comBox.addItem("北京");
			comBox.addItem("上海");
			comBox.addItem("成都");
			comBox.addItem("长春");
			add(comBox);
			
			JSlider slider = new JSlider(5, 25, 18);
			slider.setMajorTickSpacing(5);
			slider.setMinorTickSpacing(1);
	        slider.setPaintTicks(true);
	        slider.setPaintLabels(true);
	        add(slider);  
	        slider.addChangeListener(new ChangeListener() {
	            @Override
	            public void stateChanged(ChangeEvent e) {
	                text2.setText(Integer.toString(slider.getValue()));
	            }
	        });
	        text2 = new JTextField("年龄",4);
	        add(text2);
	        text2.setEditable(false);
			//area = new JTextArea(6,12);
	
			//add(new JScrollPane(area));
			
			button = new JButton("确定");
			add(button);
			
			button.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					String[] allof = new String[5];
					String name = text.getText();
					allof[0] = name;
					String city = comBox.getSelectedItem().toString();
					allof[1] = city;
					String sex = null;
					if (radio1.isSelected())
						sex = radio1.getText();
					else
						sex = radio2.getText();
					allof[2] = sex;
					String like ="";
					if(checkBox1.isSelected())
						like = checkBox1.getText();
					if(checkBox2.isSelected())
						like = checkBox2.getText()+" "+like;
					if(checkBox3.isSelected())
						like = checkBox3.getText()+" "+like;
					allof[3] = like;
					String age = Integer.toString(slider.getValue());
					allof[4] = age;
					
					for(int i = 0;i<5;i++){
						System.out.println(allof[i]);
					}
					File Student = new File(name+".txt");
					try {
						Student.createNewFile();
						FileWriter tofile = new FileWriter(name+".txt");
						BufferedWriter out = new BufferedWriter(tofile);
						for(int i = 0;i<5;i++){
							out.write(allof[i]);
							out.newLine();
						}
						JOptionPane.showMessageDialog(null, "添加成功!");
						out.close();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					System.out.println("------添加学生-----");
				}
			});	
		}
}
class DeleteStudent extends JFrame{
	public DeleteStudent(){
		//JFrame DeleteWin = new JFrame("删除窗口");
		setTitle("删除窗口");
		setVisible(true);
		setBounds(100,100,300,260);
		setLayout(new FlowLayout());
		JLabel label = new JLabel("姓名:");
		add(label);
		JTextField text = new JTextField(10);
		add(text);
		JButton button = new JButton("确认");
		add(button);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){
				String name = text.getText();
				File file = new File(name+".txt");
				try {
					file.delete();
					JOptionPane.showMessageDialog(null, "删除成功!");
				}catch(Exception e1){
					JOptionPane.showMessageDialog(null, "删除失败!");
				}
			}
		});
	}
}

class SelectStudent extends JFrame{
	
	public SelectStudent() {
		setTitle("查询窗口");
		setVisible(true);
		setBounds(100,100,300,260);
		setLayout(new FlowLayout());
		JLabel label = new JLabel("姓名:");
		add(label);
		JTextField text = new JTextField(10);
		add(text);
		JButton button = new JButton("确认");
		add(button);
		JTextArea area = new JTextArea(10,15);
		area.setEditable(false);
		add(area);
		String[] shuxing = new String[]{"姓名:","城市:","性别:","爱好:","年龄:",};
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){
				String name = text.getText();
				File file = new File(name+".txt");
				area.setText("");
				if(!file.exists()) {
					JOptionPane.showMessageDialog(null, "文件不存在!");
				}else {
					try {
						FileReader in = new FileReader(name+".txt");
						BufferedReader reader = new BufferedReader(in);
						String[] infor= new String[5];
						for(int i = 0;i<5;i++) {
							try {
								infor[i] = reader.readLine();
								area.append(shuxing[i]+infor[i]+"\n");
				
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							
						}
						
						
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				
			}
		});
	}
}

public class project4 {
	public static void main(String[] args) {
		LoginFrame logiFrame = new LoginFrame();
	}
}

5月17日更新:取消注释90、91行代码,自动创建的user.txt文件位于当前工程目录下,请在该文件中添加用户,格式为一行帐号、一行密码。

1.腾龙梦屋文章内容无特殊注明皆为源儿原创,转载请注明来源,谢谢!
2.若有相关文章侵犯您的权益,请联系源儿删除,谢谢!
3.相关软件、资料仅供学习参考使用,在24h内务必删除!
腾龙梦屋 » Java实验四(下):基于文件的小型通讯录
加速支持