import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class StudentWriteApp extends Frame implements ActionListener
{
//Declare stream objects
FileOutputStream outputStudent; //Stream to create file
ObjectOutputStream objSaveStudent; //Stream to save an object
//Declare components
TextField txtStudentName = new TextField(20);
TextField txtAddress = new TextField(20);
TextField txtResults = new TextField(25);
Button btnSave = new Button("Save");
Button btnBack = new Button("Back");
public static void main(String args[])
{
//Declare an instance of this application
StudentWriteApp thisApp = new StudentWriteApp();
thisApp.openStream();
thisApp.createInterface();
}
public void openStream()
{
try
{
//Create file and object output streams
outputStudent = new FileOutputStream("Student.txt");
objSaveStudent = new ObjectOutputStream(outputStudent);
}
catch(Exception error)
{
System.err.println("Error opening file");
}
}
public void closeStream()
{
try
{
objSaveStudent.close(); //Close the object output stream
outputStudent.close(); //Close the file output stream
}
catch (IOException error)
{
System.err.println("Error closing file");
}
}
public void createInterface()
{
//Set up user interface for this frame
setTitle("Save Student Objects");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent event)
{
closeStream();
System.exit(0);
}
});
setLayout(new FlowLayout());
add(new Label("Student Name "));
add(txtStudentName);
txtStudentName.requestFocus();
add(new Label("Address "));
add(txtAddress);
add(new Label("Results "));
add(txtResults);
add(btnSave);
add(btnBack);
btnSave.addActionListener(this);
btnBack.addActionListener(this);
txtStudentName.addActionListener(this);
txtAddress.addActionListener(this);
txtResults.addActionListener(this);
setSize(300, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == btnBack)
{
this.setVisible(false);
FrontPage pass = new FrontPage();
pass.setVisible(true);
}
//Save Student object
try
{
Student empCurrent = new Student(txtStudentName.getText(),
txtAddress.getText(),
txtResults.getText());
objSaveStudent.writeObject(empCurrent);
//objSaveStudent.flush();
txtStudentName.setText("");
txtAddress.setText("");
txtResults.setText("");
txtStudentName.requestFocus();
}
catch(Exception error)
{
System.err.println("Error writing to file");
}
}
}
Ciarant 0 Newbie Poster
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
Ciarant 0 Newbie Poster
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
Ciarant 0 Newbie Poster
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
Ciarant 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.