HW4 Solutions Page
Return to
homework page.
//
// HW5 solution to D and D 20.8. Solution to written problem follows this one.
//
//
// FileName: PhoneBookEntry.java
//
// Purpose: contains the PhoneBookEntry class definition. This class captures
// an individual entry in a phone book. i.e., it stores first name, last name,
// and phone number. It has accessor methods for these values
// It also has a compareTo method used for inserting an entry
// and finding an entry in a TreeSet. Finally, its toString()
// method can be used to make it print out correctly in a JList
import java.util.*;
import java.io.*;
public class PhoneBookEntry implements Comparable, Serializable
{
private String firstName;
private String lastName;
private String phoneNumber;
//
// Constructor Name: PhoneBookEntry()
//
// Purpose: initializes name and phone numbers to be
// empty strings. We don't have a constructor
// to set up an entry as this made it is easier
// to do validation on the fields if can return a
// a value.
//
public PhoneBookEntry()
{
firstName="";
lastName="";
phoneNumber="";
}
//
// Method Name: create
//
// Purpose: used to set up name and phone numbers
// stored in a phone entry. Performs validation
// of phone number at same time.
//
public boolean create(String fName, String lName, String pNumber)
{
setFirstName(fName);
setLastName(lName);
if(setPhoneNumber(pNumber)) return true;
else return false;
}
//
// Accessor Methods -- setPhoneEntry checks to make sure
// entry is a legal phone number
//
public void setFirstName(String fName)
{
firstName=fName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lName)
{
lastName=lName;
}
public String getLastName()
{
return lastName;
}
public boolean setPhoneNumber(String pNumber)
{
char tmp;
if(pNumber.length() != 7) return false;
for(int i=0; i < 7; i++)
{
tmp=pNumber.charAt(i);
if(tmp<'0' || tmp>'9') return false;
}
phoneNumber=pNumber;
return true;
}
public String getPhoneNumber()
{
return phoneNumber;
}
//
// Method Name: compareTo
//
// Purpose: used to check if a given entry is
// equal, larger or smaller that another.
// Notice this is only based on name.
// not phone number. This function is
// used by TreeSet.
public int compareTo(Object o)
{
if(!(o instanceof PhoneBookEntry)) return -1;
PhoneBookEntry p= (PhoneBookEntry) o;
int last = lastName.compareTo(p.lastName);
if(last==0) return firstName.compareTo(p.firstName);
else return last;
}
//
// Method Name: toString
//
// Purpose: converts phone entry to a string that can be displayed.
// Will be used by JList.
//
public String toString()
{
return lastName+" "+firstName+" "+phoneNumber;
}
}
//
// FileName: PhoneBookServer.java
//
// Purpose: this file contains the RMI interface used to get and modify
// entries from the PhoneBookServerImpl
//
import java.rmi.*;
public interface PhoneBookServer extends Remote
{
public PhoneBookEntry[] getPhoneBook() throws RemoteException;
public void addEntry( PhoneBookEntry entry) throws RemoteException;
public void modifyEntry( PhoneBookEntry entry) throws RemoteException;
public void deleteEntry( PhoneBookEntry entry) throws RemoteException;
}
//
// FileName: PhoneBookServerImpl
//
// Purpose: This is the server in our RMI example. It implements the
// PhoneBookServer interface. The phone book itself is
// stored in a TreeSet.
//
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.net.*;
import java.util.*;
public class PhoneBookServerImpl extends UnicastRemoteObject
implements PhoneBookServer
{
TreeSet listings; // where our phone book stored. TreeSets
// are sorted data structure. Uses
// compareTo for sorting.
//
// Method Name: getPhoneBookEntry
//
// Purpose: returns all phone book entries stored on the server
// in sorted order as an array. Note as TreeSet
// stores Objects casting it toArray method to
// a PhoneBookEntry[] didn't seem to work. That's
// why the code is less elegant below.
//
public PhoneBookEntry[] getPhoneBook() throws RemoteException
{
PhoneBookEntry[] tmp;
Object tmpEntry;
Iterator it;
int i=0;
if( !listings.isEmpty())
{
tmp = new PhoneBookEntry[listings.size()];
it = listings.iterator();
while(it.hasNext())
{
tmpEntry = it.next();
if(tmpEntry instanceof PhoneBookEntry)
{
tmp[i] = (PhoneBookEntry)tmpEntry;
i++;
}
}
return tmp;
}
// even if listings is empty we returns something so the
// clients JList won't be null.
tmp = new PhoneBookEntry[1];
tmp[0] = new PhoneBookEntry();
tmp[0].create("Phone Book","Empty","0000000");
return tmp;
}
//
// Remainging accessor methods. These are all straigthforward.
//
public void addEntry( PhoneBookEntry entry) throws RemoteException
{
listings.add(entry);
}
public void modifyEntry( PhoneBookEntry entry) throws RemoteException
{
listings.remove(entry);
listings.add(entry);
}
public void deleteEntry( PhoneBookEntry entry) throws RemoteException
{
listings.remove(entry);
}
public PhoneBookServerImpl() throws RemoteException
{
listings = new TreeSet();
}
public static void main( String[] args) throws Exception
{
PhoneBookServerImpl m = new PhoneBookServerImpl();
Naming.rebind("PhoneBookServer",m );
System.out.println("Server Ready");
}
}
/**
* PhoneBookClient.java
*
* Title: RMI Phone Book Client
* Description: This is the client for RMI setup. The reason this file has javadoc
* comments is that it was developed using a RAD
* development tool in Codewarrior. The PhoneBookClient
* class below contains main for the client. Otheerwise,
* all it does is create a PhoneFrame object and display
* it. PhoneFrame is the heart of the client.
*
* @author cpollett
* @version
*/
import javax.swing.*;
public class PhoneBookClient {
public PhoneBookClient() {
try {
PhoneFrame frame = new PhoneFrame();
frame.initComponents();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
// Main entry point
static public void main(String[] args) {
new PhoneBookClient();
}
}
/**
* PhoneFrame.java
*
* Title: RMI Phone Book Client
* Description: PhoneFrame is the JFrame for the client.
* It sets up the buttons and listeners and handles
* all communication with the PhoneServerImpl
* server class. This was developed with a RAD tool.
* This is why the layout for the frames content
* pane is set to null. It's so the layout tool can use
* absolute positioning.
* @author cpollett
* @version
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.util.*;
public class PhoneFrame extends javax.swing.JFrame {
PhoneBookServer listings; //object used to communicate to
// server with
// IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
// every time the form is saved. All manual changes will be overwritten.
// BEGIN GENERATED CODE
// member declarations
javax.swing.JLabel PhoneEntryLabel = new javax.swing.JLabel();
javax.swing.JButton ModifyButton = new javax.swing.JButton();
javax.swing.JButton AddButton = new javax.swing.JButton();
javax.swing.JButton DeleteButton = new javax.swing.JButton();
javax.swing.JScrollPane PhoneListScrollPane = new javax.swing.JScrollPane();
javax.swing.JList PhoneList = new javax.swing.JList();
// END GENERATED CODE
//
// Constructor Name: PhoneFrame()
//
// Purpose: connects with PhoneBookServer
//
public PhoneFrame() throws Exception {
// here's where we connect with the server
listings =
(PhoneBookServer)Naming.lookup("PhoneBookServer");
}
public void initComponents() throws Exception {
// IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
// every time the form is saved. All manual changes will be overwritten.
// BEGIN GENERATED CODE
// the following code sets the frame's initial state
PhoneEntryLabel.setSize(new java.awt.Dimension(170, 30));
PhoneEntryLabel.setLocation(new java.awt.Point(70, 20));
PhoneEntryLabel.setVisible(true);
PhoneEntryLabel.setText("Phone Entries");
PhoneEntryLabel.setToolTipText("Phone Entry Label");
ModifyButton.setSize(new java.awt.Dimension(100, 30));
ModifyButton.setLocation(new java.awt.Point(110, 210));
ModifyButton.setVisible(true);
ModifyButton.setText("Modify");
AddButton.setSize(new java.awt.Dimension(100, 30));
AddButton.setLocation(new java.awt.Point(10, 210));
AddButton.setVisible(true);
AddButton.setText("Add Entry");
AddButton.setToolTipText("Add an entry to a phone book");
AddButton.setFont(new java.awt.Font("Dialog", 1, 10));
DeleteButton.setSize(new java.awt.Dimension(90, 30));
DeleteButton.setLocation(new java.awt.Point(210, 210));
DeleteButton.setVisible(true);
DeleteButton.setText("Delete");
PhoneListScrollPane.setSize(new java.awt.Dimension(210, 150));
PhoneListScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_NEVER);
PhoneListScrollPane.setLocation(new java.awt.Point(40, 50));
PhoneListScrollPane.setVisible(true);
PhoneListScrollPane.setToolTipText("Scroll Pane for Phone list");
PhoneListScrollPane.getViewport().add(PhoneList);
PhoneList.setSelectionBackground(java.awt.Color.lightGray);
PhoneList.setVisible(true);
PhoneList.setToolTipText("List of Phone Entries");
PhoneList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
setLocation(new java.awt.Point(0, 0));
setSize(new java.awt.Dimension(309, 252));
setBackground(java.awt.Color.white);
getContentPane().setLayout(null);
setTitle("hw4.PhoneFrame");
getContentPane().add(PhoneEntryLabel);
getContentPane().add(ModifyButton);
getContentPane().add(AddButton);
getContentPane().add(DeleteButton);
getContentPane().add(PhoneListScrollPane);
ModifyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
ModifyButtonActionPerformed(e);
}
});
AddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
AddButtonActionPerformed(e);
}
});
DeleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DeleteButtonActionPerformed(e);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
thisWindowClosing(e);
}
});
// END GENERATED CODE
try
{
PhoneList.setListData(listings.getPhoneBook());
PhoneList.setSelectedIndex(0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
private boolean mShown = false;
public void addNotify() {
super.addNotify();
if (mShown)
return;
// resize frame to account for menubar
JMenuBar jMenuBar = getJMenuBar();
if (jMenuBar != null) {
int jMenuBarHeight = jMenuBar.getPreferredSize().height;
Dimension dimension = getSize();
dimension.height += jMenuBarHeight;
setSize(dimension);
}
mShown = true;
}
// Close the window when the close box is clicked
void thisWindowClosing(java.awt.event.WindowEvent e) {
setVisible(false);
dispose();
System.exit(0);
}
//
// ButtonActionPerformed handlers
//
// To keep things simple if we need to get data from the
// user or warn the user we use JOptionPane's.
//
public void DeleteButtonActionPerformed(ActionEvent e)
{
PhoneBookEntry p = (PhoneBookEntry)PhoneList.getSelectedValue();
try
{
listings.deleteEntry(p);
PhoneList.setListData(listings.getPhoneBook());
PhoneList.setSelectedIndex(0);
}
catch(RemoteException r)
{
r.printStackTrace();
}
}
public void AddButtonActionPerformed(ActionEvent e) {
String fName="", lName="", pNumber="";
PhoneBookEntry p = new PhoneBookEntry();
boolean create= true;
fName= JOptionPane.showInputDialog("Please enter a first name");
if(fName == null ) create=false;
else lName= JOptionPane.showInputDialog("Please enter a last name");
if(lName == null ) create=false;
else pNumber= JOptionPane.showInputDialog("Please enter a phone number");
if(pNumber == null ) create=false;
if(create && p.create(fName,lName,pNumber))
{
try
{
listings.addEntry(p);
PhoneList.setListData(listings.getPhoneBook());
PhoneList.setSelectedIndex(0);
}
catch(RemoteException r)
{
r.printStackTrace();
}
}
else
{
if(!create)
JOptionPane.showMessageDialog(this, "No entry created.", "Warning",
JOptionPane.WARNING_MESSAGE);
else
JOptionPane.showMessageDialog(this, "Phone number needs to be 7 digits.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public void ModifyButtonActionPerformed(ActionEvent e) {
PhoneBookEntry p = (PhoneBookEntry)PhoneList.getSelectedValue();
String pNumber = JOptionPane.showInputDialog("Please enter a new phone number");
if(pNumber == null )
{
JOptionPane.showMessageDialog(this, "No entry created.", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
if(!p.setPhoneNumber(pNumber))
{
JOptionPane.showMessageDialog(this, "Phone number needs to be 7 digits.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
try
{
listings.deleteEntry(p);
listings.addEntry(p);
PhoneList.setListData(listings.getPhoneBook());
PhoneList.setSelectedIndex(0);
}
catch(RemoteException r)
{
r.printStackTrace();
}
}
}
//
//
// HW4 solution to written problem
//
//
/*
Mysql Employee database used for solution.
At home using Linux which is why didn't use an Access DB
*/
/*
We begin with the database schema. Was lazy did not put in constraints.
Not supported by mysql anyway.
*/
CREATE TABLE Employee (
firstName VARCHAR(15) NOT NULL,
lastName VARCHAR(15) NOT NULL,
SSN CHAR(9) NOT NULL,
securityClearance INTEGER NOT NULL,
seniorityStep INTEGER NOT NULL,
salary INTEGER NOT NULL,
PRIMARY KEY(SSN)
);
/* insert a row so database is not empty. */
insert into Employee values ('Bob','Smith', '111222333','0','1','10000');
/**
* EmployeeDB.java
*
* Title: JDBCEmployee
* Description: A program to connect to and manipulate an Employee
* database. This program was developed
* with Codewarrior's RAD tool which is why
* it's in two files. This file just basically
* contains main which sets up an EmployeeFrame.
* This latter class is where are the action
* is.
* @author cpollett
* @version
*/
import javax.swing.*;
public class EmployeeDB {
public EmployeeDB() {
try {
EmployeeFrame frame = new EmployeeFrame();
frame.initComponents();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
// Main entry point
static public void main(String[] args) {
new EmployeeDB();
}
}
/**
* EmployeeFrame.java
*
* Title: JDBCEmployee
* Description: Frame used by our EmployeeDB. This file
* sets up an displays the GUI components
* used for interacting with the Employee
* database. It also handles the connections
* and any statements executed on the database.
*
* @author cpollett
* @version
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class EmployeeFrame extends javax.swing.JFrame {
// IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
// every time the form is saved. All manual changes will be overwritten.
// BEGIN GENERATED CODE
// member declarations
javax.swing.JPanel SSSPanel = new javax.swing.JPanel();
javax.swing.JTextArea SeniorityArea = new javax.swing.JTextArea();
javax.swing.JTextArea SalaryArea = new javax.swing.JTextArea();
javax.swing.JTextArea SecArea = new javax.swing.JTextArea();
javax.swing.JLabel SecurityLabel = new javax.swing.JLabel();
javax.swing.JLabel SeniorityLabel = new javax.swing.JLabel();
javax.swing.JLabel SalaryLabel = new javax.swing.JLabel();
javax.swing.JButton UpdateSearchButton = new javax.swing.JButton();
javax.swing.JButton CreateButton = new javax.swing.JButton();
javax.swing.JPanel FLSPanel = new javax.swing.JPanel();
javax.swing.JTextArea LNameArea = new javax.swing.JTextArea();
javax.swing.JTextArea SSNArea = new javax.swing.JTextArea();
javax.swing.JTextArea FNameArea = new javax.swing.JTextArea();
javax.swing.JLabel FirstNameLabel = new javax.swing.JLabel();
javax.swing.JLabel LastNameLabel = new javax.swing.JLabel();
javax.swing.JLabel SSNLabel = new javax.swing.JLabel();
javax.swing.JPanel AdvancedPanel = new javax.swing.JPanel();
javax.swing.JButton AdvancedAddToDBButton = new javax.swing.JButton();
javax.swing.JButton AdvancedButton = new javax.swing.JButton();
javax.swing.JPanel NormalPanel = new javax.swing.JPanel();
javax.swing.JButton NormalAddToDBButton = new javax.swing.JButton();
javax.swing.JButton NormalButton = new javax.swing.JButton();
javax.swing.JPanel PreviousNextPanel = new javax.swing.JPanel();
javax.swing.JButton PreviousButton = new javax.swing.JButton();
javax.swing.JButton NextButton = new javax.swing.JButton();
javax.swing.JButton UpdateButton = new javax.swing.JButton();
// END GENERATED CODE
Connection connection; // our database connection
Statement statement; // query or command we're executing
ResultSet rset; // its result set
//
// Constructor Name: EmployeeFrame()
//
// Purpose: loads database driver and connects to database.
// This is the only part of the program where there
// should be a difference between using a
// MySql database rather than an Access one.
//
public EmployeeFrame() {
try
{
Class.forName("org.gjt.mm.mysql.Driver" ).newInstance();
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/employee?user=cpollett&password=cpollett");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
System.exit(1);
}
}
public void initComponents() throws Exception {
// IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
// every time the form is saved. All manual changes will be overwritten.
// BEGIN GENERATED CODE
// the following code sets the frame's initial state
SSSPanel.setSize(new java.awt.Dimension(280, 120));
SSSPanel.setLocation(new java.awt.Point(90, 180));
SSSPanel.setVisible(false);
SSSPanel.setLayout(null);
SSSPanel.add(SeniorityArea);
SSSPanel.add(SalaryArea);
SSSPanel.add(SecArea);
SSSPanel.add(SecurityLabel);
SSSPanel.add(SeniorityLabel);
SSSPanel.add(SalaryLabel);
SeniorityArea.setSize(new java.awt.Dimension(110, 20));
SeniorityArea.setLocation(new java.awt.Point(170, 50));
SeniorityArea.setVisible(true);
SalaryArea.setSize(new java.awt.Dimension(110, 20));
SalaryArea.setLocation(new java.awt.Point(170, 90));
SalaryArea.setVisible(true);
SecArea.setSize(new java.awt.Dimension(110, 20));
SecArea.setLocation(new java.awt.Point(170, 10));
SecArea.setVisible(true);
SecurityLabel.setSize(new java.awt.Dimension(150, 20));
SecurityLabel.setLocation(new java.awt.Point(0, 10));
SecurityLabel.setVisible(true);
SecurityLabel.setText("Security Clearance:");
SeniorityLabel.setSize(new java.awt.Dimension(150, 20));
SeniorityLabel.setLocation(new java.awt.Point(0, 50));
SeniorityLabel.setVisible(true);
SeniorityLabel.setText("Seniority Level:");
SalaryLabel.setSize(new java.awt.Dimension(150, 20));
SalaryLabel.setLocation(new java.awt.Point(0, 90));
SalaryLabel.setVisible(true);
SalaryLabel.setText("Salary:");
UpdateSearchButton.setSize(new java.awt.Dimension(150, 30));
UpdateSearchButton.setLocation(new java.awt.Point(240, 10));
UpdateSearchButton.setVisible(true);
UpdateSearchButton.setText("Update/Search");
CreateButton.setSize(new java.awt.Dimension(150, 30));
CreateButton.setLocation(new java.awt.Point(80, 10));
CreateButton.setVisible(true);
CreateButton.setText("Create");
FLSPanel.setSize(new java.awt.Dimension(280, 120));
FLSPanel.setLocation(new java.awt.Point(90, 60));
FLSPanel.setVisible(false);
FLSPanel.setLayout(null);
FLSPanel.add(LNameArea);
FLSPanel.add(SSNArea);
FLSPanel.add(FNameArea);
FLSPanel.add(FirstNameLabel);
FLSPanel.add(LastNameLabel);
FLSPanel.add(SSNLabel);
LNameArea.setSize(new java.awt.Dimension(110, 20));
LNameArea.setLocation(new java.awt.Point(170, 50));
LNameArea.setVisible(true);
SSNArea.setSize(new java.awt.Dimension(110, 20));
SSNArea.setLocation(new java.awt.Point(170, 90));
SSNArea.setVisible(true);
FNameArea.setSize(new java.awt.Dimension(110, 20));
FNameArea.setLocation(new java.awt.Point(170, 10));
FNameArea.setVisible(true);
FirstNameLabel.setSize(new java.awt.Dimension(150, 20));
FirstNameLabel.setLocation(new java.awt.Point(0, 10));
FirstNameLabel.setVisible(true);
FirstNameLabel.setText("First Name:");
LastNameLabel.setSize(new java.awt.Dimension(150, 20));
LastNameLabel.setLocation(new java.awt.Point(0, 50));
LastNameLabel.setVisible(true);
LastNameLabel.setText("Last Name:");
SSNLabel.setSize(new java.awt.Dimension(150, 20));
SSNLabel.setLocation(new java.awt.Point(0, 90));
SSNLabel.setVisible(true);
SSNLabel.setText("SSN:");
AdvancedPanel.setSize(new java.awt.Dimension(390, 30));
AdvancedPanel.setLocation(new java.awt.Point(30, 310));
AdvancedPanel.setVisible(false);
AdvancedPanel.setLayout(null);
AdvancedPanel.setBackground(java.awt.Color.lightGray);
AdvancedPanel.add(AdvancedAddToDBButton);
AdvancedPanel.add(AdvancedButton);
AdvancedAddToDBButton.setSize(new java.awt.Dimension(160, 30));
AdvancedAddToDBButton.setLocation(new java.awt.Point(230, 0));
AdvancedAddToDBButton.setVisible(true);
AdvancedAddToDBButton.setText("Add to Database");
AdvancedButton.setSize(new java.awt.Dimension(160, 30));
AdvancedButton.setLocation(new java.awt.Point(0, 0));
AdvancedButton.setVisible(true);
AdvancedButton.setText("Advanced");
NormalPanel.setSize(new java.awt.Dimension(390, 30));
NormalPanel.setLocation(new java.awt.Point(30, 310));
NormalPanel.setVisible(false);
NormalPanel.setLayout(null);
NormalPanel.setBackground(java.awt.Color.lightGray);
NormalPanel.add(NormalAddToDBButton);
NormalPanel.add(NormalButton);
NormalAddToDBButton.setSize(new java.awt.Dimension(160, 30));
NormalAddToDBButton.setLocation(new java.awt.Point(230, 0));
NormalAddToDBButton.setVisible(true);
NormalAddToDBButton.setText("Add to Database");
NormalButton.setSize(new java.awt.Dimension(160, 30));
NormalButton.setLocation(new java.awt.Point(0, 0));
NormalButton.setVisible(true);
NormalButton.setText("Normal");
PreviousNextPanel.setSize(new java.awt.Dimension(390, 30));
PreviousNextPanel.setLocation(new java.awt.Point(30, 310));
PreviousNextPanel.setVisible(false);
PreviousNextPanel.setLayout(null);
PreviousNextPanel.setBackground(java.awt.Color.lightGray);
PreviousNextPanel.add(PreviousButton);
PreviousNextPanel.add(NextButton);
PreviousNextPanel.add(UpdateButton);
PreviousButton.setSize(new java.awt.Dimension(120, 30));
PreviousButton.setLocation(new java.awt.Point(0, 0));
PreviousButton.setVisible(true);
PreviousButton.setText("Previous");
NextButton.setSize(new java.awt.Dimension(120, 30));
NextButton.setLocation(new java.awt.Point(260, 0));
NextButton.setVisible(true);
NextButton.setText("Next");
UpdateButton.setSize(new java.awt.Dimension(120, 30));
UpdateButton.setLocation(new java.awt.Point(130, 0));
UpdateButton.setVisible(true);
UpdateButton.setText("Update");
setLocation(new java.awt.Point(0, 0));
setSize(new java.awt.Dimension(467, 340));
setBackground(java.awt.Color.white);
getContentPane().setLayout(null);
setTitle("JDBCEmployee.EmployeeFrame");
getContentPane().add(SSSPanel);
getContentPane().add(UpdateSearchButton);
getContentPane().add(CreateButton);
getContentPane().add(FLSPanel);
getContentPane().add(AdvancedPanel);
getContentPane().add(NormalPanel);
getContentPane().add(PreviousNextPanel);
UpdateSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
UpdateSearchButtonActionPerformed(e);
}
});
CreateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
CreateButtonActionPerformed(e);
}
});
AdvancedAddToDBButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
AdvancedAddToDBButtonActionPerformed(e);
}
});
AdvancedButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
AdvancedButtonActionPerformed(e);
}
});
NormalAddToDBButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
NormalAddToDBButtonActionPerformed(e);
}
});
NormalButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
NormalButtonActionPerformed(e);
}
});
PreviousButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
PreviousButtonActionPerformed(e);
}
});
NextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
NextButtonActionPerformed(e);
}
});
UpdateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
UpdateButtonActionPerformed(e);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
thisWindowClosing(e);
}
});
// END GENERATED CODE
}
private boolean mShown = false;
public void addNotify() {
super.addNotify();
if (mShown)
return;
// resize frame to account for menubar
JMenuBar jMenuBar = getJMenuBar();
if (jMenuBar != null) {
int jMenuBarHeight = jMenuBar.getPreferredSize().height;
Dimension dimension = getSize();
dimension.height += jMenuBarHeight;
setSize(dimension);
}
mShown = true;
}
// Close the window when the close box is clicked
void thisWindowClosing(java.awt.event.WindowEvent e) {
try
{
connection.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
setVisible(false);
dispose();
System.exit(0);
}
//
// ButtonActionEvent handlers -- these functions handle
// the events from clicking on various buttons.
//
public void NormalButtonActionPerformed(java.awt.event.ActionEvent e) {
CreateButtonActionPerformed(e);
}
public void AdvancedButtonActionPerformed(java.awt.event.ActionEvent e) {
FLSPanel.setVisible(true);
SSSPanel.setVisible(true);
AdvancedPanel.setVisible(false);
NormalPanel.setVisible(true);
PreviousNextPanel.setVisible(false);
}
public void NormalAddToDBButtonActionPerformed(java.awt.event.ActionEvent e)
{
boolean insertSuccess=false;
if(validateFields())
{
String insertString="insert into Employee values ('"+
FNameArea.getText()+"',"+
"'"+LNameArea.getText()+"',"+
"'"+SSNArea.getText()+"',"+
"'"+SecArea.getText()+"',"+
"'"+SeniorityArea.getText()+"',"+
"'"+SalaryArea.getText()+"')";
try
{
statement = connection.createStatement();
statement.executeUpdate(insertString);
statement.close();
insertSuccess=true;
}
catch(Exception ex)
{
ex.printStackTrace();
insertSuccess=false;
}
}
if(insertSuccess)
JOptionPane.showMessageDialog(
this,"Insert successful","Info",JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(
this,"Insert error","Info",JOptionPane.ERROR_MESSAGE);
}
public void AdvancedAddToDBButtonActionPerformed(java.awt.event.ActionEvent e) {
NormalAddToDBButtonActionPerformed(e);
}
public void PreviousButtonActionPerformed(java.awt.event.ActionEvent e)
{
try
{
if(!checkChangeQuery(e))
{
if(rset.isFirst())
rset.last();
else rset.previous();
}
getRowText();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void NextButtonActionPerformed(java.awt.event.ActionEvent e) {
try
{
if(!checkChangeQuery(e))
{
if(rset.isLast())
rset.first();
else rset.next();
}
getRowText();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void UpdateButtonActionPerformed(java.awt.event.ActionEvent e) {
boolean updateSuccess=false;
if(validateFields())
{
try
{
String fName = rset.getString(1);
String lName = rset.getString(2);
String ssn = rset.getString(3);
String sec = rset.getString(4);
String sen = rset.getString(5);
String sal = rset.getString(6);
rset.close();
statement.close();
statement = connection.createStatement();
statement.executeUpdate("update Employee set "+
"firstName='"+FNameArea.getText()+"',"+
"lastName='"+LNameArea.getText()+"',"+
"SSN='"+SSNArea.getText()+"',"+
"securityClearance='"+SecArea.getText()+"',"+
"seniorityStep='"+SeniorityArea.getText()+"',"+
"salary='"+SalaryArea.getText()+"' where "+
"firstname='"+fName+"' and "+
"lastName='"+lName+"' and "+
"SSN='"+ssn+"' and "+
"securityClearance='"+sec+"' and "+
"seniorityStep='"+sen+"' and "+
"salary='"+sal+"'"
);
statement.close();
UpdateSearchButtonActionPerformed(e);
updateSuccess=true;
}
catch(Exception ex)
{
ex.printStackTrace();
updateSuccess=false;
}
}//end validateFields
if(updateSuccess)
JOptionPane.showMessageDialog(
this,"Update successful","Info",JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(
this,"Update error","Info",JOptionPane.ERROR_MESSAGE);
}
public void CreateButtonActionPerformed(java.awt.event.ActionEvent e) {
FLSPanel.setVisible(true);
SSSPanel.setVisible(false);
AdvancedPanel.setVisible(true);
NormalPanel.setVisible(false);
PreviousNextPanel.setVisible(false);
FNameArea.setText("");
LNameArea.setText("");
SSNArea.setText("");
SecArea.setText("0");
SeniorityArea.setText("0");
SalaryArea.setText("8000");
}
public void UpdateSearchButtonActionPerformed(java.awt.event.ActionEvent e) {
FLSPanel.setVisible(true);
SSSPanel.setVisible(true);
AdvancedPanel.setVisible(false);
NormalPanel.setVisible(false);
PreviousNextPanel.setVisible(true);
try
{
statement = connection.createStatement();
rset = statement.executeQuery("select * from Employee");
if(rset.next())
getRowText();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public boolean checkChangeQuery(ActionEvent e) throws SQLException
{
int change =0;
if(rset.getString(1).equals(FNameArea.getText())) change++;
if(rset.getString(2).equals(LNameArea.getText())) change++;
if(rset.getString(3).equals(SSNArea.getText())) change++;
if(rset.getString(4).equals(SecArea.getText())) change++;
if(rset.getString(5).equals(SeniorityArea.getText())) change++;
if(rset.getString(6).equals(SalaryArea.getText())) change++;
if(change!=6)
{
rset.close();
statement.close();
statement = connection.createStatement();
//in standard SQL (unlike Access) % is the wild card symbol
rset = statement.executeQuery("select * from Employee "+
"where (firstName like '"+FNameArea.getText()+"%' and "+
"lastName like '"+LNameArea.getText()+"%' and "+
"SSN like '"+SSNArea.getText()+"%' and "+
"securityClearance like '"+SecArea.getText()+"%' and "+
"seniorityStep like '"+SeniorityArea.getText()+"%' and "+
"salary like '"+SalaryArea.getText()+"%')"
);
if(!rset.next())
{
rset.close();
statement.close();
UpdateSearchButtonActionPerformed(e);
}
return true;
}
return false;
}
public void getRowText() throws SQLException
{
FNameArea.setText(rset.getString(1));
LNameArea.setText(rset.getString(2));
SSNArea.setText(rset.getString(3));
SecArea.setText(rset.getString(4));
SeniorityArea.setText(rset.getString(5));
SalaryArea.setText(rset.getString(6));
}
//
// Method Name: validateFields
//
// Purpose: used to check if the fields in the book
// entry a valid to add to database.
//
public boolean validateFields()
{
String SSN= SSNArea.getText();
String security = SecArea.getText();
String seniority = SeniorityArea.getText();
String salary = SalaryArea.getText();
int sec,sen,sal;
char SSNChar;
if(SSN.length() != 9) return false;
for(int i=0; i<9; i++)
{
SSNChar = SSN.charAt(i);
if(SSNChar<'0' || SSNChar>'9') return false;
}
try
{
sec = Integer.parseInt(security);
sen = Integer.parseInt(seniority);
sal = Integer.parseInt(salary);
}
catch(NumberFormatException num)
{
return false;
}
if(sec<0 || sec> 5) return false;
if(sen<0 || sen> 10) return false;
if(sal < 0) return false;
return true;
}
}
|