Question

Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by...

Java: student directory GUI

You need to implement three classes:

Person

Student

StudentDirectory

StudentMain

Start by implementing Person and Student classes. Once you are sure you can serialize and deserialize and ArrayList of Students to and from a file, move on to building the GUI application.

Person:

The Person class should implement serializable interface. It contains the following:

Person's first name (String)

Person's last name (String)

Person's id number

Person's date of birth (Date)

public String toString(): This method method should return the following string (without \n) for a person with id=1111, firstName="Joe", lastName="Smith", dob="01-25-1990":
1111 Joe Smith 01-25-1990

The Person class should implement all getter and setter methods for these data members.

Student:

The Student class is a subclass of Person, it should implement serializable. Student will have to employ custom serialization. That is, it needs to implement storeObject(...) and retrieveObject(...) methods (see below), and Person needs to have a 0-param constructor.

Student's college (String)

public void storeObject(ObjectOutputStream out) throws IOException

public Student retrieveObject(ObjectInputStream in) throws IOException, ClassNotFoundException

public String toString() method: This method is to add college name (in brackets) to the result of Person.toString() . So, for the above example if "Joe Smith" is a student at "Art&Sci" college. The output of the toString method should be:
1111 Joe Smith 01-25-1990 [Art&Sci]

StudentDirectory:

The StudentDirectory class is a GUI program that is used for retrieving/storing an ArrayList of Students from/to the file named "StudentsList.dat" using the serialization mechanism. StudentDirectory is a subclass of JFrame. It has a menu, and a few labels, textboxes, and buttons as described below:

Initially when executed, your program should load the ArrayList of Students into memory (you should implement a method for this purpose (i.e. loading) since this functionality is needed later as well). You can do this in the constructor of StudentDirectory. Then your program should show the information of the first Student of the ArrayList as described below. The very first time you run the program, there is no "StudentsList.dat" file. Your program should start as if the "Append" button is clicked (see below).

Your program should have a "File" menu with three menu-items: "Load", "Save", "Exit".

"Load" loads the ArrayList of Students from the above file into memory.

"Save" saves the ArrayList of Students into the above file.

"Exit" terminates the program.

For each attribute of the Student class, including the ones that are defined in Person, you need to have a textbox with an appropriate label preceding it.

For "dob" you can use three comboboxes to let user pick month, day, and year.

You also need a label to show the index of the current Student in the ArrayList.

You also need three buttons at the bottom of your frame: Previous, Next, Append.

The "Previous" button goes back to the preceding Student in the ArrayList. This button should be disabled if we are at the beginning of the ArrayList.

The "Next" button shows the succeeding Student in the ArrayList. This button should be disabled if we are at the end of the ArrayList.

Hitting the "Append" button clears all the textboxes and lets user enter information for a new Student. Also, the text on the "Append" button should change to "Submit". Once the user entered the information, he can press "Submit" to append the Student to the ArrayList. If he decided he does not want to do so, he can simply hit "Previous" to cancel changes and go to the last Student in the list.

Automatically save the ArrayList to file when the frame is closed.

StudentMain:

The StudentMain class is the program with the main method where you need to create your JFrame (i.e. StudentDirectoy) object and display it.

Things to note:

Your program should not crash due to any exceptions. However, in case of IOExceptions you can gracefully terminate your program and inform the user of the problem by showing an informative dialog box (use JOptionPane for this, the following is an example).

 //custom title, error icon
 JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane error", JOptionPane.ERROR_MESSAGE);
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the code for the question. Please dont forget to rate the answer if it helped . Thank you very much.

Person.java

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Person implements Serializable{
   /**
   *
   */
   private static final long serialVersionUID = -5660806033412038928L;
   protected String fname;
   protected String lname;
   protected String id;
   protected Date dob;
   private static final SimpleDateFormat sdf=new SimpleDateFormat("MM-dd-yyyy");
  
   public Person()
   {
       fname="";
       lname="";
       id="";
       dob=new Date();
   }
   public String getFname() {
       return fname;
   }
   public void setFname(String fname) {
       this.fname = fname;
   }
   public String getLname() {
       return lname;
   }
   public void setLname(String lname) {
       this.lname = lname;
   }
   public String getId() {
       return id;
   }
   public void setId(String id) {
       this.id = id;
   }
   public Date getDob() {
       return dob;
   }
   public void setDob(Date dob) {
       this.dob = dob;
   }
  
   public String toString()
   {
       return id+" "+fname+" "+lname+" "+sdf.format(dob);
   }
  
}

Student.java

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

public class Student extends Person {

   /**

   *

   */

   private static final long serialVersionUID = 622900950946744538L;

   protected String college;

   public Student()

   {

       super();

       college="";

   }

   public String getCollege() {

       return college;

   }

   public void setCollege(String college) {

       this.college = college;

   }

   public String toString()

   {

       return super.toString()+" "+"["+college+"]";

   }

}

StudentDirectory.java

import java.awt.BorderLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.Date;

import javax.swing.BorderFactory;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class StudentDirectory extends JFrame implements ActionListener {

   JTextField txtId,txtFname,txtLname,txtCollege;

   JComboBox cmbDay,cmbMonth,cmbYear;

   JButton butPrev,butNext,butAppend;

   private static final SimpleDateFormat sdf=new SimpleDateFormat("M-d-yyyy");

   private static final Calendar calendar=Calendar.getInstance();

  

   ArrayList<Student> students;

   private String studentsFile;

   private int current;

   public StudentDirectory()

   {

       super("Student Directory");

       studentsFile= null;

       students=new ArrayList<Student>();

       current=0;

       createUI();

       setSize(600,400);

      

       addWindowListener(new WindowAdapter() {

           @Override

           public void windowClosing(WindowEvent e) {

               saveToFile();

               System.exit(0);

           }

          

          

       });

       loadFromFile();

       setVisible(true);

   }

   private void createUI()

   {

       createMenu();

       createCenterPanel();

   }

  

   private void createCenterPanel()

   {

       JPanel center=new JPanel();

      

       center.setBorder(BorderFactory.createTitledBorder("Student Details"));

       center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));

      

       JLabel l = new JLabel("ID: ");

       txtId = new JTextField();

       l.setLabelFor(txtId);

       center.add(l);

       center.add(txtId);

              

       l = new JLabel("First Name: ");

       txtFname = new JTextField();

       l.setLabelFor(txtFname);

       center.add(l);

       center.add(txtFname);

              

       l = new JLabel("Last Name: ");

       txtLname = new JTextField();

       l.setLabelFor(txtLname);

       center.add(l);

       center.add(txtLname);

      

       l = new JLabel("Date of Birth: ");

         

       l.setLabelFor(txtLname);

       center.add(l);

       center.add(txtLname);

       JPanel pDob=new JPanel();

       String list[]=new String[31];

       for(int i=1;i<32;i++)

           list[i-1]=i+"";

      

       cmbDay=new JComboBox(list);

      

       list=new String[]{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

       cmbMonth=new JComboBox(list);

      

       int end=Calendar.getInstance().get(Calendar.YEAR),start=end-35;

       list =new String[end-start+1];

       for(int i=0;start+i<=end;i++)

           list[i]=start+i+"";

       cmbYear = new JComboBox(list);

       pDob.add(cmbDay);

       pDob.add(cmbMonth);

       pDob.add(cmbYear);

       l.setLabelFor(pDob);

      

       center.add(l);

       center.add(pDob);

      

       l = new JLabel("College: ");

       txtCollege = new JTextField();

       l.setLabelFor(txtCollege);

       center.add(l);

       center.add(txtCollege);

      

       JPanel pBut=new JPanel();

         

      butPrev=new JButton("Previous");

      butPrev.setActionCommand("Previous");

      butPrev.addActionListener(this);

       pBut.add(butPrev);

      

       butNext=new JButton("Next");

       butNext.setActionCommand("Next");

       butNext.addActionListener(this);

       pBut.add(butNext);

      

       butAppend=new JButton("Append");

       butAppend.setActionCommand("Append");

       butAppend.addActionListener(this);

       pBut.add(butAppend);

      

              

       center.add(pBut);

       getContentPane().add(center);

   }

  

   private void createMenu()

   {

       JMenu mFile = new JMenu("File");

       String fileMenuOptions[]={"Load","Save","Exit"};

       JMenuItem mItem;

       for(int i=0;i<fileMenuOptions.length;i++)

       {  

           mItem=new JMenuItem(fileMenuOptions[i]);

           mItem.setActionCommand(fileMenuOptions[i]);

           mFile.add(mItem);

           mItem.addActionListener(this);

       }

       JMenuBar menuBar=new JMenuBar();

       menuBar.add(mFile);

       setJMenuBar(menuBar);

      

   }

   @Override

   public void actionPerformed(ActionEvent e){

       String action = e.getActionCommand();

       if(action.equals("Load"))

       {

           loadFromFile();

       }

       else if(action.equals("Save"))

       {

           saveToFile();

       }

       else if(action.equals("Exit"))

       {

           saveToFile();

           System.exit(0);

       }

       else if(action.equals("Previous"))

       {

             

           if(current>0)

           {

               current--;

           }

           displayCurrent();

                 

       }

       else if(action.equals("Next"))

       {

           if(current<students.size()-1)

           {

               current++;

           }

           displayCurrent();

                 

       }

       else if(action.equals("Append"))

       {

          

           butAppend.setText("Submit");

           butAppend.setActionCommand("Submit");

           butPrev.setEnabled(true);

           butNext.setEnabled(false);

           clearFields();

       }

       else if(action.equals("Submit"))

       {

           if(!isError())

           {

               Student s=new Student();

               s.setId(txtId.getText());

               s.setFname(txtFname.getText());

               s.setLname(txtLname.getText());

               s.setCollege(txtCollege.getText());

                 

               String date=cmbDay.getSelectedItem().toString(),month=cmbMonth.getSelectedIndex()+1+"",year=cmbYear.getSelectedItem().toString();

               try {

                   s.setDob(sdf.parse(month+"-"+date+"-"+year));

               } catch (ParseException e1) {

                   JOptionPane.showMessageDialog(this, "Invalid date of birth!");

                   return ;

               }

               students.add(s);

              

               current=students.size()-1;

               displayCurrent();

           }

       }

      

   }

   private void changeToAppend()

   {

       butAppend.setText("Append");

       butAppend.setActionCommand("Append");

      

   }

   private void clearFields()

   {

       txtId.setText("");

       txtFname.setText("");

       txtLname.setText("");

       cmbDay.setSelectedIndex(0);

       cmbMonth.setSelectedIndex(0);

       cmbYear.setSelectedIndex(0);

       txtCollege.setText("");

   }

   private void displayCurrent()

   {

       Student s;

       if(!students.isEmpty())

       {

           s=students.get(current);

           txtId.setText(s.getId());

           txtFname.setText(s.getFname());

           txtLname.setText(s.getLname());

           txtCollege.setText(s.getCollege());

           calendar.setTime(s.getDob());

              

           cmbDay.setSelectedIndex(calendar.get(Calendar.DATE)-1);

           cmbMonth.setSelectedIndex(calendar.get(Calendar.MONTH));

           cmbYear.setSelectedItem(""+calendar.get(Calendar.YEAR));

          

           if(current==0)

           {

               butPrev.setEnabled(false);

              

           }

           else

               butPrev.setEnabled(true);

          

           if(current==students.size()-1)

           {

               butNext.setEnabled(false);

                 

           }

           else

               butNext.setEnabled(true);

           changeToAppend();

       }

      

      

   }

   private boolean isError()

   {

       String str;

       str=txtId.getText();

       if(str==null || str.trim().equals(""))

       {

           JOptionPane.showMessageDialog(this, "Enter a valid ID!");

           return true;

       }

       str=txtFname.getText();

       if(str==null || str.trim().equals(""))

       {

           JOptionPane.showMessageDialog(this, "Enter a valid First Name!");

           return true;

       }

       str=txtLname.getText();

       if(str==null || str.trim().equals(""))

       {

           JOptionPane.showMessageDialog(this, "Enter a valid Last Name!");

           return true;

       }

      

       str=txtCollege.getText();

       if(str==null || str.trim().equals(""))

       {

           JOptionPane.showMessageDialog(this, "Enter a valid College!");

           return true;

       }

      

       return false;

   }

   private void saveToFile()

   {

       String filename=studentsFile;

       if(filename==null)

         

       filename=JOptionPane.showInputDialog("Enter filename:");

       if(filename==null)

       {

           JOptionPane.showMessageDialog(this, "Filename not specified. File not saved!");

           return;

       }

          

          

       studentsFile=filename;

       ObjectOutputStream oos;

       try {

           oos = new ObjectOutputStream(new FileOutputStream(studentsFile));

           oos.writeObject(students);

           oos.flush();

           oos.close();

       } catch (IOException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

      

   }

  

   private void loadFromFile()

   {

         

       String filename;

          

       filename=JOptionPane.showInputDialog("Enter filename:");

       if(filename==null)

           return;

         

       studentsFile=filename;   

       try {

           ObjectInputStream ois=new ObjectInputStream(new FileInputStream(studentsFile));

           students = (ArrayList<Student>)ois.readObject();

           ois.close();

           displayCurrent();

       } catch (FileNotFoundException e) {

             

       } catch (IOException e) {

           JOptionPane.showMessageDialog(this, "Exception occured: "+e.getMessage());

           System.exit(1);

       } catch (ClassNotFoundException e) {

           JOptionPane.showMessageDialog(this, "Exception occured: "+e.getMessage());

           System.exit(1);

       }  

   }

}

StudentMain.java

public class StudentMain {

   public static void main(String[] args) {

      

         

       StudentDirectory studUI=new StudentDirectory();

      

   }

}

output

Add a comment
Know the answer?
Add Answer to:
Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person...

    Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person and Student represent individuals with a first and last name as String class variables, and Student has an additional int class variable that represents a ID number. The Roster class represents a group of people that are objects of either the Person or Student class. It contains an ArrayList. The Person class has been completed for you with class variables, a constructor, and a...

  • Implement an abstract class named Person and two subclasses named Student and Staff in Java. A person has a name, address, phone number and e-mail address. A student has a credit hour status (freshman...

    Implement an abstract class named Person and two subclasses named Student and Staff in Java. A person has a name, address, phone number and e-mail address. A student has a credit hour status (freshman, sophomore, junior, or senior). Define the possible status values using an enum. Staff has an office, salaray, and date-hired. Implement the above classes in Java. Provide Constructors for classes to initialize private variables. Getters and setters should only be provided if needed. Override the toString() method...

  • Develop a set of classes for a college to use in various student service and personnel applications. Classes you need to design include the following: • Person — A Person contains the following fields...

    Develop a set of classes for a college to use in various student service and personnel applications. Classes you need to design include the following: • Person — A Person contains the following fields, all of type String: firstName, lastName, address, zip, phone. The class also includes a method named setData() that sets each data field by prompting the user for each value and a display method that displays all of a Person’s information on a single line at the...

  • GUI programming

    Please use netBeans Exercise 4:A librarian needs to keep track of the books he has in his Library.1. Create a class Book that has the following attributes: ISBN, Title, Author, Subject, and Price. Choose anappropriate type for each attribute.2. Add a static member BookCount to the class Book and initialize it to zero.3. Add a default constructor for the class Book. Increment the BookCount static member variable and an initialization constructor for the class Book. Increment the BookCount in all constructors.4....

  • Implement a superclass Person. Make two classes, Student and Instructor, that inherit from Person. A person...

    Implement a superclass Person. Make two classes, Student and Instructor, that inherit from Person. A person has a name and a year of birth. A student has a major, and an instructor has a salary. Writhe the class definitions, the constructors, and the methods toString for all classes. For Person the constructors should include a no-arg constructor and one that accepts in the name of the person. For student there should be a no-arg constructor and a constructor that accepts...

  • For task 2, implement the three classes (Person, Student, and Staff) that are described above. Note...

    For task 2, implement the three classes (Person, Student, and Staff) that are described above. Note that classes Staff and Student are derived from the superclass Person -- in other words Staff and Student inherit from Person. Make sure that the subclasses Student and Staff invoke the superclass' constructors and correctly inherit the variables and methods from the superclass Person. Also note that Person is an abstract class. <abstract> Person -name:String -address:String = “String” +getName():String +getAddress():String +setAddress(address:String):void +setName(name:String):void Staff -school:String...

  • I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student...

    I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student {    private String name;    private double gpa;    private int idNumber;    public Student() {        this.name = "";        this.gpa = 0;        this.idNumber = 0;    }    public Student(String name, double gpa, int idNumber) {        this.name = name;        this.gpa = gpa;        this.idNumber = idNumber;    }    public Student(Student s)...

  • Create a java project and create Student class. This class should have the following attributes, name...

    Create a java project and create Student class. This class should have the following attributes, name : String age : int id : String gender : String gpa : double and toString() method that returns the Student's detail. Your project should contain a TestStudent class where you get the student's info from user , create student's objects and save them in an arralist. You should save at least 10 student objects in this arraylist using loop statement. Then iterate through...

  • In Java. Write a GUI contact list application. The program should allow you to input names...

    In Java. Write a GUI contact list application. The program should allow you to input names and phone numbers. You should also be able to input a name and have it display the previously entered phone number. The GUI should look something like the following, although you are welcome to format it in any way that works. This should be a GUI application with a JFrame. The program should contain two arrays of Strings. One array will contain a list...

  • Java Programming Design a class named Person and its two subclasses named Student and Employee. A...

    Java Programming Design a class named Person and its two subclasses named Student and Employee. A person has a name, address, phone number, and email address. A student has a class status (freshman, sophomore, junior, or senior). Define the status as a constant. An employee has an office, salary, date hired. Define a class named MyDate that contains the fields year, month, and day. Override the toString method in each class to display the class name and the person's name....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT