import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class Directory extends JFrame{
ArrayList <Client> ab= new
ArrayList<Client>();
TextField name,number;
Button ad = new Button("add"),
sv = new
Button("save"),
ld = new
Button("load");
String sName="",sNumber="";
JPanel pc;
JScrollPane pname;
JTextArea text;
Directory(){
setBounds(80, 80, 450, 400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
pc = new JPanel();
pc.setLayout(new FlowLayout());
text = new JTextArea(20,10);
pname = new JScrollPane(text);
name=new TextField("",15);
number=new TextField("",15);
number.addActionListener(new
Add());
ad.addActionListener(new Add());
text.setEditable(false);
pc.add(name);
pc.add(number);
pc.add(ad);
pc.add(sv);
pc.add(ld);
sv.addActionListener(new Save());
ld.addActionListener(new Load());
add("North",pc);
add("Center",pname);
setVisible(true);
}
class Add implements ActionListener{
public void
actionPerformed(ActionEvent e){
sName=name.getText();
sNumber=number.getText();
if(sName.length()==0){
name.setText("??");
return;
}
if(sNumber.length()==0){
number.setText("??");
return;
}
ab.add(new
Client(sName,sNumber));
text.append(sName+"\t"+sNumber+"\n");
name.setText("");
number.setText("");
}
}
class Save implements ActionListener{
public void
actionPerformed(ActionEvent e){
try{
ObjectOutputStream os = new ObjectOutputStream(new
FileOutputStream("data.dat"));
os.writeObject(ab);
os.close();
}
catch(FileNotFoundException ex){
System.out.println("Can't save the file data.dat");
}
catch(IOException ex){}
}
}
class Load implements ActionListener{
public void
actionPerformed(ActionEvent e){
try{
ObjectInputStream os = new ObjectInputStream(new
FileInputStream("data.dat"));
ab = (ArrayList<Client>) os.readObject();
os.close();
text.setText("");
for(Client cl:ab){
text.append(cl.name+"\t"+cl.number+"\n");
}
}
catch(FileNotFoundException ex){
System.out.println("Can't find the file data.dat");
}
catch(IOException ex){
ex.printStackTrace();
}
catch
(ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
public static void main(String arg[]){
new Directory();
}
}
class Client implements Serializable {
String name, number;
public Client(String name, String number){
this.name = name;
this.number = number;
}
}