/*
* Created by: Gsquare
* Purpose: This framed application stores contact information added by the user.
* Last Modified: 26/10/06
*/
////////////////////////////////////
/**** Import Packages from API ****/
////////////////////////////////////
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
// the class with the main method which runs the frame and displays my cool logo
public class EasyPlannerApp
{
public static void main(String[] args)
{
// My current logo =D -> try to find the smiley
System.out.println("Created by:");
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
System.out.println("%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%");
System.out.println("%~ ~%");
System.out.println("%~ GGGGGGGGG SSSSSSSSS QQQQQQQQQ UU UU AAAAAAAAA RRRRRRRRR EEEEEEEEE ~%");
System.out.println("%~ GGGGGGGGG SSSSSSSSS QQQQQQQQQ UU UU AAAAAAAAA RRRRRRRRR EEEEEEEEE ~%");
System.out.println("%~ GG-----GG SS------- QQ-----QQ UU O O UU AA-----AA RR-----RR EE------- ~%");
System.out.println("%~ GG -- SS QQ QQ UU UU AA AA RR RR EE ~%");
System.out.println("%~ GG SS QQ QQ UU UU AA AA RR RR EE ~%");
System.out.println("%~ GG SSSSSSSSS QQ QQ UU U UU AA AA RR RR EEEEEE ~%");
System.out.println("%~ GG GGGG SSSSSSSSS QQ QQ UU UU AAAAAAAAA RRRRRRRRR EEEEEE ~%");
System.out.println("%~ GG GGGG -------SS QQ QQ UU UU AAAAAAAAA RRRRRRRRR EE---- ~%");
System.out.println("%~ GG GG SS QQ QQQ UU UU AA-----AA RR---RR EE ~%");
System.out.println("%~ GG GG SS QQ QQ UU UU AA AA RR RR EE ~%");
System.out.println("%~ GGGGGGGGG SSSSSSSSS QQQQQQQQQQ UUUUUUUUU AA AA RR RR EEEEEEEEE ~%");
System.out.println("%~ GGGGGGGGG SSSSSSSSS QQQQQQQQQ UUUUUUUUU AA AA RR RR EEEEEEEEE ~%");
System.out.println("%~ ~%");
System.out.println("%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%");
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
// creates frame using EasyPlannerFrame's constructor
JFrame frame = new EasyPlannerFrame();
frame.pack();// packs the frame's components to decrease unused space
frame.setVisible(true);// sets the frame visible
}
}
// the class which creates the frame using the EasyPlannerPanel class for its panels
class EasyPlannerFrame extends JFrame
{
public EasyPlannerFrame()
{
// sets frame
setTitle("The Easy Planner");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// creates and adds main panel
JPanel panel = new EasyPlannerPanel();
this.add(panel);
// attempts to center window using method coded below, may not work with different screen sizes
centerWindow(this);
}
private void centerWindow(Window w)
{
Toolkit tk = Toolkit.getDefaultToolkit();// creates a Toolkit object
Dimension d = tk.getScreenSize();// creates a Dimension object using the Toolkit object
setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
// sets the frames location to the width/2 and the height/2
}
}
// the class which creates the panels for the frame, which include components and event handlers
class EasyPlannerPanel extends JPanel implements ActionListener
{
/////////////////////////////////////////
/**** Objects/Variables Declaration ****/
/////////////////////////////////////////
private JList contactList;// list of contacts' names
private JButton newContactButton,// creates new contact
editContactButton,// edits selected contact's information
deleteContactButton,// delets selected contact
acceptButton,// saves changes to contact
cancelButton;// cancels changes to contact
private JLabel contactNameLabel,// takes in name String
contactPhoneNumberLabel,// takes in phone number String
contactAddressLabel,// takes in address String
contactEmailLabel;// takes in email String
private JTextField contactNameTextField,// takes name
contactPhoneNumberTextField, // takes phone number
contactAddressTextField,// takes address
contactEmailTextField;// takes email
boolean newContactButtonPressed,// verifies that the new contact button was pressed
editContactButtonPressed;// verifies that the edit contact button was pressed
// the constructor of the class, containing all the panels and their components
public EasyPlannerPanel()
{
setLayout(new BorderLayout());// sets main panel layout
// creates Border object for use in panels
Border loweredBorder = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
// creates file if inexistant
try
{
// creates file name
String easyPlannerContactsFile = "EasyPlannerContacts.txt";
// creates file
File contactsFile = new File(easyPlannerContactsFile);
if (!contactsFile.exists())// if file doesn't exist, then create new
{ // objects in order not to overwrite saved data
contactsFile.createNewFile();
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
//////////////////////////////
/**** Contact List Panel ****/
//////////////////////////////
JPanel contactListPanel = new JPanel();// creates Contact List Panel
contactListPanel.setLayout(new GridBagLayout());// sets panel layout
// borders and labels "Contact List"
contactListPanel.setBorder(BorderFactory.createTitledBorder(loweredBorder, "Contact List"));
// JList settings
contactList = new JList();
updateContactList();
contactList.setFixedCellWidth(150);
contactList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// displays JList contact on selection
ListSelectionListener contactListListener = new ListSelectionListener()// creates listener object
{
public void valueChanged(ListSelectionEvent e)// called whenever value changes
{
newContactButtonPressed = false;
editContactButtonPressed = false;
enableButtons(false);
setTextFieldsEditable(false);
String selectedName;
int index = e.getLastIndex();// gets index number of selected item on list
Object selectedNameObject = contactList.getSelectedValue();// gets object value of item
if (selectedNameObject != null)// checks to see if the object is null
{
selectedName = selectedNameObject.toString();// changes object item to String item
}
else
{
selectedName = " ";// sets it as a space
}
String easyPlannerContactsFile = "EasyPlannerContacts.txt";// file's name
try
{
// creates reader object
BufferedReader in = new BufferedReader(
new FileReader(easyPlannerContactsFile));// creates reader
{
String nameLine, name, phoneNumber, address, email;
String separater = "\t";
int nameIndex;
ArrayList<String> contactNameArray = new ArrayList<String>();
nameLine = in.readLine();// reads first line of file
while (nameLine != null)// loop continues until there is no next line
{
String[] contactArray = nameLine.split(separater);
// creates an array of the items stored on the line by separating all the strings
// wherever there is a separater (tab)
name = contactArray[0];// locates name -> all characters before first separater
if (selectedName.equals(name))// if read name = selected name then this
// displays that contact's information
{
// sets contact information variables
phoneNumber = contactArray[1];
address = contactArray[2];
email = contactArray[3];
// sets text fields to information variables
contactNameTextField.setText(name);
contactPhoneNumberTextField.setText(phoneNumber);
contactAddressTextField.setText(address);
contactEmailTextField.setText(email);
break;// exits loop once correct name is found to increase speed rather
// than look at the rest of the names for no reason =)
}
nameLine = in.readLine();// sets variable to read the next line (if null, ends loop)
}
in.close();// closes reader
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
};
contactList.addListSelectionListener(contactListListener);// adds list selection listener
JScrollPane contactListScroll = new JScrollPane(contactList,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);// creates scrollbar
// adds list and scrollbar to Contact List panel
contactListPanel.add(contactListScroll, getConstraints(0,0,GridBagConstraints.REMAINDER,1,0,0,
GridBagConstraints.CENTER,GridBagConstraints.BOTH));
add(contactListPanel, BorderLayout.WEST);// adds Contact List panel to main panel
/////////////////////////////////////
/**** Contact Information Panel ****/
/////////////////////////////////////
JPanel contactInformationPanel = new JPanel();// creates panel for Contact Information
contactInformationPanel.setLayout(new GridBagLayout());// sets layout
contactInformationPanel.setBorder(BorderFactory.createTitledBorder
(loweredBorder, "Contact Information"));// borders and labels "Contact Information"
// sets label titles
contactNameLabel = new JLabel("* Name:");
contactPhoneNumberLabel = new JLabel("Phone Number:");
contactAddressLabel = new JLabel("Address:");
contactEmailLabel = new JLabel("Email:");
// sets uneditable text field for each label
contactNameTextField = new JTextField("Enter Name");
contactPhoneNumberTextField = new JTextField("Enter Phone Number");
contactAddressTextField = new JTextField("Enter Address");
contactEmailTextField = new JTextField("Enter Email");
setTextFieldsEditable(false);
// sets buttons titles
acceptButton = new JButton("Accept");
cancelButton = new JButton("Cancel");
enableButtons(false);
// adds action listeners to buttons
acceptButton.addActionListener(this);
cancelButton.addActionListener(this);
// adds labels, button and text fields to panel, while setting constraints (method explained below)
contactInformationPanel.add(contactNameLabel, getConstraints(0,0,1,1,0,0,
GridBagConstraints.EAST,GridBagConstraints.NONE));
contactInformationPanel.add(contactNameTextField, getConstraints(1,0,1,1,0,0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL));
contactInformationPanel.add(contactPhoneNumberLabel, getConstraints(0,1,1,1,0,0,
GridBagConstraints.EAST,GridBagConstraints.NONE));
contactInformationPanel.add(contactPhoneNumberTextField, getConstraints(1,1,1,1,0,0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL));
contactInformationPanel.add(contactAddressLabel, getConstraints(0,2,1,1,0,0,
GridBagConstraints.EAST,GridBagConstraints.NONE));
contactInformationPanel.add(contactAddressTextField, getConstraints(1,2,1,1,0,0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL));
contactInformationPanel.add(contactEmailLabel, getConstraints(0,3,1,1,0,0,
GridBagConstraints.EAST,GridBagConstraints.NONE));
contactInformationPanel.add(contactEmailTextField, getConstraints(1,3,1,1,0,0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL));
contactInformationPanel.add(acceptButton, getConstraints(0,4,1,1,0,0,
GridBagConstraints.CENTER,GridBagConstraints.NONE));
contactInformationPanel.add(cancelButton, getConstraints(1,4,1,1,0,0,
GridBagConstraints.CENTER,GridBagConstraints.NONE));
add(contactInformationPanel, BorderLayout.EAST);// adds Contact Information panel to main panel
/////////////////////////////////////////
/**** New/Edit/Delete Contact Panel ****/
/////////////////////////////////////////
JPanel contactNewEditDeletePanel = new JPanel();// creates panel for New/Edit/Delete Contact
contactNewEditDeletePanel.setLayout(new FlowLayout(FlowLayout.CENTER));// sets panel layout
contactNewEditDeletePanel.setBorder(BorderFactory.createTitledBorder(loweredBorder));// borders New/Edit Contact
// sets buttons
newContactButton = new JButton("New Contact");
editContactButton = new JButton("Edit Contact");
deleteContactButton = new JButton("Delete Contact");
// adds action listeners
newContactButton.addActionListener(this);
editContactButton.addActionListener(this);
deleteContactButton.addActionListener(this);
// adds buttons to New/Edit Contact panel
contactNewEditDeletePanel.add(newContactButton);
contactNewEditDeletePanel.add(editContactButton);
contactNewEditDeletePanel.add(deleteContactButton);
add(contactNewEditDeletePanel, BorderLayout.SOUTH);// adds New/Edit Contact panel to main panel
}
public GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight,
int ipadx, int ipady, int anchor, int fill)// used to set up component when being added to panel
{
GridBagConstraints c = new GridBagConstraints(); // creates GridBagConstraints object
c.insets = new Insets(5,5,5,5); // sets space around the component
c.gridx = gridx;// sets 'x' coordinate of component on the grid
c.gridy = gridy;// sets 'y' coordinate of component on the grid
c.gridwidth = gridwidth;// sets number of cells component uses going right
c.gridheight = gridheight;// sets number of cells component uses going downwards
c.ipadx = ipadx;// resizes width of component
c.ipady = ipady;// resizes height of component
c.anchor = anchor;// sets alignment of component in cell
c.fill = fill;// sets type of fill for component in cell
return c;// returns the object with these settings
}
public void setTextFieldsEditable(boolean tf)
// sets text fields editable/uneditable
{
contactNameTextField.setEditable(tf);
contactPhoneNumberTextField.setEditable(tf);
contactAddressTextField.setEditable(tf);
contactEmailTextField.setEditable(tf);
}
public void clearTextFields()// clears text fields for creating new contact
{
contactNameTextField.setText("");
contactPhoneNumberTextField.setText("");
contactAddressTextField.setText("");
contactEmailTextField.setText("");
}
public void enableButtons(boolean tf)// enables accept and cancel buttons for adding/editing contact
{
acceptButton.setEnabled(tf);
cancelButton.setEnabled(tf);
}
public void setContactToInformationPanel()
{
String selectedName = contactList.getSelectedValue().toString();
String easyPlannerContactsFile = "EasyPlannerContacts.txt", separater = "\t";
String nameLine, name, phoneNumber, address, email;
int nameIndex;
String[] contactArray;
try
{
// creates reader
BufferedReader in = new BufferedReader(
new FileReader(easyPlannerContactsFile));
{
nameLine = in.readLine();
while (nameLine != null)// searches for matching contact name in file
{
// gets name
nameIndex = nameLine.indexOf(separater);
name = nameLine.substring(0, nameIndex);
// leaves loop if names are equal
if (name.equals(selectedName))
{
contactArray = nameLine.split(separater);// creates array of strings in line
// separated by a tab
phoneNumber = contactArray[1];// gets phone number of contact
address = contactArray[2];// gets address of contact
email = contactArray[3];// gets email of contact
// sets text fields
contactNameTextField.setText(name);
contactPhoneNumberTextField.setText(phoneNumber);
contactAddressTextField.setText(address);
contactEmailTextField.setText(email);
break;
}
nameLine = in.readLine();
}
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public boolean addContactToFile()
{
String separater = "\t";
String name = contactNameTextField.getText();
String phoneNumber = contactPhoneNumberTextField.getText();
String address = contactAddressTextField.getText();
String email = contactEmailTextField.getText();
boolean nameIsSame = false;
if (phoneNumber.equals(""))
{
phoneNumber = "?";
}
if (address.equals(""))
{
address = "?";
}
if (email.equals(""))
{
email = "?";
}
if (phoneNumber.length() > 2 && phoneNumber.startsWith(" "))
phoneNumber = "?";
if (address.length() > 2 && address.startsWith(" "))
address = "?";
if (email.length() > 2 && email.startsWith(" "))
email = "?";
// creates file name
String easyPlannerContactsFile = "EasyPlannerContacts.txt";
// creates file
File contactsFile = new File(easyPlannerContactsFile);
try
{
if (!contactsFile.exists())// if file doesn't exist, then creates a new file
{
contactsFile.createNewFile();
}
// creates reader object
BufferedReader in = new BufferedReader(
new FileReader(easyPlannerContactsFile));// creates reader
{
String nameLine, nameToCheck;
int nameIndex;
ArrayList<String> contactNameArray = new ArrayList<String>();
nameLine = in.readLine();// reads first line of file
while (nameLine != null)// loop continues until there is no next line
{
String[] contactArray = nameLine.split(separater);
// creates an array of the items stored on the line by separating all the strings
// wherever there is a separater (tab)
nameToCheck = contactArray[0];// locates name -> all characters before first separater
if (name.equals(nameToCheck) && !editContactButtonPressed)// if read name = selected name then this
// displays that contact's information
{
String message = "Please do not use a name already saved.";
JOptionPane.showMessageDialog(this, message,
"Incorrect Data", JOptionPane.ERROR_MESSAGE);
nameIsSame = true;
break;// exits loop once correct name is found to increase speed rather
// than look at the rest of the names for no reason =)
}
nameLine = in.readLine();// sets variable to read the next line (if null, ends loop)
}
in.close();// closes reader
}
if (!nameIsSame)
{
// creates writer object and sets to append -> added text is at the end of the file
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(contactsFile, true)));
out.println(name + separater + phoneNumber + separater +
address + separater + email);// prints the contact information + a separater (tab)
// in between for reading purposes
out.close();// flushes and closes the writer
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return !nameIsSame;
}
public boolean removeContactFromFile()
{
boolean contactIsSelected = false;// returns true if a contact is selected
String nameLine;
int nameIndex;
String separater = "\t";
String easyPlannerContactsFile = "EasyPlannerContacts.txt";// creates file name
File contactsFile = new File(easyPlannerContactsFile);// creates file
ArrayList<String> contactFileArray = new ArrayList<String>();// creates ArrayList for file
String[] contactNameArray;// creates array for names
if (contactList.getSelectedIndex() != -1)// if an item is selected
{
contactIsSelected = true;
String contactName = contactList.getSelectedValue().toString();// name from JList
try
{
// Step 1: make an array of all lines on contact file
// creates reader object
BufferedReader in = new BufferedReader(
new FileReader(easyPlannerContactsFile));// creates reader
nameLine = in.readLine();// reads first line of file
while (nameLine != null)// loops until there is no next line
{
contactFileArray.add(nameLine);// adds line to ArrayList
nameLine = in.readLine();// sets variable to read the next line (if null, ends loop)
}
in.close();// closes reader
// Step 2: identify name of contact to be deleted
for (int i = 0; i < contactFileArray.size(); i++)
{
contactNameArray = contactFileArray.get(i).split(separater);
if (contactNameArray[0].equals(contactName))
{
contactFileArray.remove(i);
break;
}
}
// Step 3: overwrite the file (erase all existing data)
contactsFile.delete();// deletes old file
contactsFile.createNewFile();// creates new file
// Step 4: write new array list to file
// creates writer object and sets to append -> added text is at the end of the file
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(contactsFile, true)));
for(int i = 0; i < contactFileArray.size(); i++)
{
out.println(contactFileArray.get(i).toString());
}
out.close();// flushes and closes the writer
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
else// if an item is not selected
{
contactIsSelected = false;
}
return contactIsSelected;// returns boolean variable
}
public void updateContactList()
{
String easyPlannerContactsFile = "EasyPlannerContacts.txt";// file's name
try
{
// creates reader object
BufferedReader in = new BufferedReader(
new FileReader(easyPlannerContactsFile));
{
String nameLine, name;
String separater = "\t";
int nameIndex;
ArrayList<String> contactNameArray = new ArrayList<String>();
nameLine = in.readLine();
while (nameLine != null)// loop continues until there is no next line
{
String[] contactArray = nameLine.split(separater);
// creates an array of the items stored on the line by separating all the strings
// wherever there is a separater (tab)
name = contactArray[0];// locates name at first array index and stores it into variable
contactNameArray.add(name);// adds the name to the contact list array of names
nameLine = in.readLine();// sets variable to read the next line (if null, ends loop)
}
in.close();// closes reader
contactList.setListData(contactNameArray.toArray());// updates the JList with the new array
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
/**** Event Handling ****/
public void actionPerformed (ActionEvent e)
{
Object source = e.getSource();// gets name of button pressed
if (source == newContactButton)// actions to do if New Contact button was pressed
{
newContactButtonPressed = true;
setTextFieldsEditable(true);
clearTextFields();
enableButtons(true);
}
if (source == editContactButton)// actions to do if Edit Contact button was pressed
{
if (contactList.getSelectedIndex() != -1)// if an item is selected
{
setContactToInformationPanel();
editContactButtonPressed = true;
setTextFieldsEditable(true);
enableButtons(true);
}
else
{
String message = "Please select an existing contact you wish to edit.";
JOptionPane.showMessageDialog(this, message,
"Insufficient Data", JOptionPane.ERROR_MESSAGE);
}
}
if (source == deleteContactButton)// actions to do if Delete Contact button was pressed
{
if(newContactButtonPressed || editContactButtonPressed)
{
String message = "Please cancel other actions before deleting.";
JOptionPane.showMessageDialog(this, message,
"System Error", JOptionPane.ERROR_MESSAGE);
}
else if (removeContactFromFile())
{
updateContactList();
enableButtons(false);
setTextFieldsEditable(false);
clearTextFields();
}
else
{
String message = "Please select an existing contact you wish to delete.";
JOptionPane.showMessageDialog(this, message,
"Insufficient Data", JOptionPane.ERROR_MESSAGE);
}
}
if (source == acceptButton)// actions to do if Accept button was pressed
{
if (newContactButtonPressed)
{
editContactButtonPressed = false;
if (contactNameTextField.getText().length() != 0)
{
if (addContactToFile())// adds the contact to the file and if
// name is not already taken, returns true
{
updateContactList();// updates the contact list
enableButtons(false);
newContactButtonPressed = false;// resets the boolean after used
setTextFieldsEditable(false);
}
}
else
{
String message = "Please enter a name.";
JOptionPane.showMessageDialog(this, message,
"Insufficient Data", JOptionPane.ERROR_MESSAGE);
}
}
if (editContactButtonPressed)
{
newContactButtonPressed = false;
if (removeContactFromFile())
{
if(addContactToFile())
{
updateContactList();
enableButtons(false);
editContactButtonPressed = false;
setTextFieldsEditable(false);
}
}
else
{
String message = "Please select an existing contact you wish to edit.";
JOptionPane.showMessageDialog(this, message,
"Insufficient Data", JOptionPane.ERROR_MESSAGE);
}
}
}
if (source == cancelButton)// actions to do if Cancel button was pressed
{
newContactButtonPressed = false;
editContactButtonPressed = false;
setTextFieldsEditable(false);
enableButtons(false);
clearTextFields();
}
}
}
|