之前写过一个用户信息添加的小程序,经过一段时间的学习,再拿这个小程序出来添加了一点功能。
主要就是对象流的操作,用户打开软件就读取指定文件中的用户信息,关闭的时候就询问是否保存数据。
期间我遇到的问题:
- 读取对象流不能使用available
- 对象流的读取对象必须实现序列化接口
- 关闭窗口的时候选择取消还是关闭了窗口
解决:
- 对象流读取应该使用抓异常的方式来读取
- 对象实现序列化接口class UserInfo implements Serializable
- 关闭窗口时加上setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
下面代码
第一个类,main
public class Main{
public static void main(String[] args) {
Object provinces[] = {"江苏省","浙江省"};
Object cities[][]={
{"南京市","苏州市","无锡市","常州市"},
{"杭州市","温州市","金华市","义乌市"}
};
UserFrame u = new UserFrame (provinces,cities);
u.setVisible(true);
}
}
第二个类,JFrame
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class UserFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JTextArea tArea;
private JTextField tfNum;// 不可编辑的ID信息
private JTextField tfName;// 姓名
private JRadioButton rbMan;// 单选按钮 男
private JRadioButton rbGril;// 单选按钮 女
private JComboBox<Object> cbProvience;// 组合框 省份
private JComboBox<Object> cbCity;// 组合框 城市
private JButton btAdd;// 添加按钮
Object provinces[];
Object cities[][];
private int num = 1;
private List<UserInfo> list;
public UserFrame(Object[] provinces, Object[][] citise) {
super("用户信息");
this.provinces = provinces;
this.cities = citise;
Container container = getContentPane();
setBounds(400, 150, 500, 300);
setLayout(new GridLayout(1, 2));
// setDefaultCloseOperation(EXIT_ON_CLOSE);
// 加上这句!!取消的时候就不会关闭了
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
int i = JOptionPane.showConfirmDialog(UserFrame.this, "是否保存?");
if (i == JOptionPane.OK_OPTION) {
// 进行保存
save();
System.exit(-1);
} else if (i == JOptionPane.NO_OPTION) {
// 不保存,直接退出
System.exit(-1);
}
}
});
// 左边
tArea = new JTextArea();
tArea.setEditable(false);
list = new ArrayList<UserInfo>();
ini();// 先对集合进行初始化(读取文件)初始化使用到了tArea所以tArea必须先New
// tArea.setBackground(Color.LIGHT_GRAY);
// 添加滚动条
container.add(new JScrollPane(tArea));// container.add(tArea);
// 右边
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(6, 1));
container.add(panel);
// ID
tfNum = new JTextField("" + num);
tfNum.setEditable(false);
panel.add(tfNum);
// name
tfName = new JTextField("姓名");
panel.add(tfName);
// sex
JPanel panSex = new JPanel();
panSex.setLayout(new GridLayout(1, 2));
panel.add(panSex);
rbMan = new JRadioButton("男", true);
rbGril = new JRadioButton("女");
panSex.add(rbMan);
panSex.add(rbGril);
ButtonGroup bGroup = new ButtonGroup();
bGroup.add(rbMan);
bGroup.add(rbGril);
// 组合框
// 省份
cbProvience = new JComboBox<Object>(provinces);
panel.add(cbProvience);
cbProvience.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int index = cbProvience.getSelectedIndex();// 省份选了第几个
cbCity.removeAllItems();
for (int i = 0; i < citise[index].length; i++) {
cbCity.addItem(citise[index][i]);
}
}
});
// 城市
cbCity = new JComboBox<Object>(citise[0]);
panel.add(cbCity);
// 添加
btAdd = new JButton("添加");
panel.add(btAdd);
btAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 表现层技术边界
// 1收集参数: num(现成),name,sex,province,city
String sexString = "";
if (rbGril.isSelected()) {
sexString = "女";
} else {
sexString = "男";
}
UserInfo uf = new UserInfo();
uf.setNum(num);
uf.setName(tfName.getText());
uf.setSex(sexString);
uf.setPrivince((String) cbProvience.getSelectedItem());
uf.setCity((String) cbCity.getSelectedItem());
showTArea(uf);
tfNum.setText("" + num);
list.add(uf);// 每添加一个用户就加到集合里面
}
});
}
/*
* 将用户信息展示在textArea
*/
public void showTArea(UserInfo uf) {
if (num == 1) {
tArea.append(uf.toString());
} else {
tArea.append("\n" + uf.toString());
}
num++;
}
/*
* 对集合进行初始化(读取文件)
*/
public void ini() {
// 读取文件
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("E:/test/userInfo.llyz"));
while (true) {
UserInfo userInfo = (UserInfo) in.readObject();
showTArea(userInfo);
list.add(userInfo);
}
} catch (EOFException e) {
} catch (IOException e) {
System.err.println("文件读取失败!");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("文件没找到!");
e.printStackTrace();
} catch (Exception e) {
System.err.println("未知错误!");
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException("关流失败", e);
}
}
}
}
public void save() {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream("E:/test/userInfo.llyz"));
for (int i = 0; i < list.size(); i++) {
UserInfo userInfo = list.get(i);
out.writeObject(userInfo);
}
} catch (IOException e) {
// e.printStackTrace();
} catch (Exception e) {
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException("关流失败", e);
}
}
}
}
}
第三个类,封装用户信息的类
import java.io.Serializable;
class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
private int num;
private String name;
private String sex;
private String privince;
private String city;
public UserInfo() {
num=1;
}
public UserInfo(int num, String name, String sex, String privince, String city) {
super();
this.num = num;
this.name = name;
this.sex = sex;
this.privince = privince;
this.city = city;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPrivince() {
return privince;
}
public void setPrivince(String privince) {
this.privince = privince;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return num + "," + name + "," + sex + "," + privince + "," + city;
}
}