0% found this document useful (0 votes)
50 views

Employee Payroll Management System_Java Assignment

Uploaded by

jessielimzhimin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Employee Payroll Management System_Java Assignment

Uploaded by

jessielimzhimin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Table of Contents

CHAPTER 1: INTRODUCTION 2
1.1 Project Background 2
CHAPTER 2: RESULT 4
2.1 Login GUI 4
2.1.1 Layout 4
2.1.2 Button Listener and Database 5
2.1.3 Exception Handling 8
2.2 Admin GUI 9
2.2.1 Layout 9
2.2.2 Buttons Listener and Database 10
2.2.3 Exception Handling 19
2.3 Salary Slip GUI 20
2.3.1 Layout 20
2.3.2 Buttons Listener 21
2.3.3 Exception Handling 22
CHAPTER 3: SUMMARY 23

1
CHAPTER 1: INTRODUCTION

1.1 Project Background

Payroll management system is a software system that could generate the salary slip to the
employees while the basic salary and bonus are updated by admin. A big capacity company
could use this system to manage their employees’ payroll. This management system helps
improve employee engagement and regulatory compliance.
Our project is to develop an efficient payroll management system that able to store
employee’s data and generate an accurate net salary of the employee. As a simulation, we had
developed a UCSI University’s payroll management system by using Java Programming.
According to date of joining and date up to which salary created number of working days will
be entered. Basic pay will be defined according to the profession of employee. We had created
few position examples such as Lecturer, Janitor, Chancellor, etc. Some components like
medical allowance and bonus will be added and charges of tax will be deducted. The system
will generate the net salary based on the employee’s basic salary, earning bonus, medical
allowance, and tax deduction. Every new employee should register their data details into the
system first, such as their name, profession, date of joining the company, bank account number
and ic/passport number. The system will store their data and set their basic salary according to
their profession and working days.
We had created three Graphical User Interface (GUI) which is Login GUI, Admin GUI,
and Salary Slip GUI. Admin or employees can check their own net salary through Login GUI
to the system. If admin login, the system will bring the user to Admin GUI which could
add/delete employee’s data. If employee enters his or her ID, it will bring the employee to the
Salary Slip GUI to generate and show the net salary of employee according to his or her basic
salary, bonus, and working days. Figure 1.1 shows the flowchart of this program. In this report,
we showed all coding that we develop the payroll management system by using Java
programming.

2
Figure 1.1 shows the flowchart of the Employee Payroll Management System

3
CHAPTER 2: RESULT

2.1 Login GUI

2.1.1 Layout

Various components from both Swing and AWT libraries are used to implement the GUI
design and functionality. Components such as JButton, JPanel, JFrame, JTextField
JPasswordField are from Swing library while the actionlistener functions are from AWT library.
The combination of Swing components and AWT provides the ability to edit all components
with and without layout manager as well as allowing the nesting of panels. For example, figure
2.1 shows the nested panel to construct ‘paneladmin’ and figure 2.2 shows the design of the
LoginGUI.

Figure 2.1 shows the program use to construct paneladmin with nested panel constructed

4
Figure 2.2 shows the layout and design of the GUI

2.1.2 Button Listener and Database

Generate Salary Button


Generate Salary button is used to direct user to Salary Slip GUI after user entering his/her
employee ID. This can be done by using ActionListerner Interface is Java AWT library.
Following shows the LoginGUI implements ActionListener Interface and override the
actionPerformed method to give definition of the buttons’ action.

public class LoginGUI extends Frame implements ActionListener {


… …
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) // button1 == Generate Salary
// specify button1 action here
else if (e.getSource() == button2)
// specify button2 action here
}
}

The getSource method in ActionEvent is used to determine which event will be fired by
the component when there is more than one event listener. Thus, by using this method, we do
need need to declare multiple actionPerformed abstract method to handle different types of
events for each button.

5
Before jumping into the explanation of the codes of Generate Salary Button (button1) in
the actionPerformed method, let us see the methods in database class that are used in generating
salary slip. The first method in the database class is used is ‘search_employee_salaryslip’
method which accept employee’s ID as parameter. Following show the definition of the method:

public ResultSet search_employee_salaryslip (int id) {


try
{
Connection connect = connection();
query = "SELECT Employee_name, Employee_id, salary, bonus FROM
employee WHERE Employee_id = ?";
PreparedStatement preparestmt = connect.prepareStatement(query);
preparestmt.setInt(1, id);
output_db = preparestmt.executeQuery();
return output_db;
}
catch(Exception ex)
{
System.err.print("Got an exception!");
System.err.println(ex.getMessage());
return null;
}
}

The ‘search_employee_salaryslip’ method is used to search for employee’s details in the


database such as name, id, salary, and bonus where the id parameter is used to indicate which
employee should the database be looking for.

Connection connect = connection();


query = "SELECT Employee_name, Employee_id, salary, bonus FROM
employee WHERE Employee_id = ?";
PreparedStatement preparestmt = connect.prepareStatement(query);
preparestmt.setInt(1, id);
output_db = preparestmt.executeQuery();

Above code show the parameterized query to be sent to database, then the preparestmt that
is declare under PreparedStatement Interface will be used to point to Connection object to
connect to database and executes parameterized query using methods of PreparedStatement
interface which are setInt method and executeQuery method. In the setInt method, we need to
provide two parameters which are the parameterized index in the query and value in the
database, and both share the same data type which are Integer. Finally, we can use the
executeQuery method to execute query that return instance of ResultSet. ‘output_db’ is used
to store the instance of ‘ResultSet’. ‘ResultSet’ is an interface that represents the result of a
database query, in another words, it contains the record that we want. All these codes will be

6
stored inside the try block to catch ‘Exception’ ensure the program will not be stopped when
unexpected events occur. We will discuss more on the Exception handling later. As mentioned
previously, the id is used to tell the database which employee it should be looking for, thus if
the database successfully found the employee, it will return the result named under ‘output_db’
variable else it will return null.
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
String emp_id = userid.getText().toString();
try {
int id = Integer.parseInt(emp_id);
try {
ResultSet result = db.search_employee_salaryslip(id);
if (result.next()) {
double bonus = result.getDouble("bonus");
String Name_out = result.getString("Employee_name");
String basic_salary_out = result.getString("salary");
double basic_salary =
Double.parseDouble(basic_salary_out);
SalarySlip dialog = new SalarySlip(id, Name_out, basic_salary,
bonus)
frame1.dispose();
}else
JOptionPane.showMessageDialog(button1, "No Employee found.
Please ensure your ID is correct!");
}catch (SQLException | NullPointerException ex) {
JOptionPane.showMessageDialog(button1, "Salary not set yet");}
}catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(button1, "Invalid Input");}
}
Above code shows the ‘search_employee_salaryslip’ method is invoked and returned
value from the method will be store in result variable. Then using ‘next’ method in the
ResultSet, it will move to the next row of the result. Usually, it is used with a while loop to
collect the output in the result; however, in here, we just want to check if the employee ID
exists in the database or not, thus we use if-else-then logic. If the employee ID is correct then
it will do the action in the if block; else, the action will be printed out “No employee found”
message to the user using Java Swing component which is JOptionPane.
Finally, the program will move on to sending all the data in the result to Salary Slip GUI.
Following codes show how the program works:
String Name_out = result.getString("Employee_name").toString();
String basic_salary_out = result.getString("salary").toString();
double basic_salary = Double.parseDouble(basic_salary_out);
SalarySlip dialog = new SalarySlip(id, Name_out, basic_salary, bonus);
frame1.dispose();

7
Admin Login Button
Admin Login is used to direct user to adminGUI where admin can carry out administrative task. It
also has the validation function to check if the username and password are correct or not to access
the database.
Initially we wanted to implement a method to set the username and password of the admin to
our database’s password and username. However, not everyone is using database, thus, we decided
to hardcode the admin’s password and username into our program. Following shows the action
performed by admin login button:

else if (e.getSource() == button2) {


String stradmin = adminname.getText().toString();
String strpass = password.getText().toString();
if (stradmin.equals("admin") && strpass.equals("admin")) {
frame1.dispose();
admin_page = new adminGUI();
}
else
{
JOptionPane.showMessageDialog(button2, "Invalid Username or Password");
}
}

2.1.3 Exception Handling

Generate Salary Button


We are able to catch few events that user entered wrong input in the employee ID text field.
Following show the events that we catch to prevent the program from crashing:
• ID contains characters other than Integer
• ID entered cannot be found in database
• Salary is not updated by admin yet
To prevent user from entering an ID other than integer, we used a build-in method in
Integer class which is ‘parseInt’ method to cast the string value to integer. By doing this, we
are able to check if the value entered by employee contains other unwanted characters such as
alphabets and symbols or not. This line of code will be placed inside the try-catch block, in the
event of user entering value other than numbers, program will jump to catch block which will
be used to catch Number Format Exception error. Following shows the code of try-catch block:
try {
int id = Integer.parseInt(emp_id);
… …
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(button1, "Invalid Input");}

8
To validate user’s ID exist in database or not, as discussed in the 2.1.2 Buttons Listener
and Database, search_employee_salaryslip is used and if-else-then logic is used to validate.
Another condition we need to check is the salary value has been set by the admin or not,
if the salary is not set yet, it will print another message to the user, for example, in the following
code:
catch (SQLException | NullPointerException ex) {
JOptionPane.showMessageDialog(button1, "Salary not set yet");

It is in the catch block under ‘NullPointerException’ class. This class will be thrown when
there is a null value in the object. In another words, if the row of employee in the table has null
value, it will go to catch block to catch the NullPointerException and print “Salary not set yet”
message to the user. However, ‘bonus’ is different as it is not paid monthly, thus the if-else-
then logic is used here to give the bonus value to zero if it is null in the database.
2.2 Admin GUI

2.2.1 Layout

The adminGUI which is used to carry out administrative task is built and design using 3
main panels, each panel has various panels nested inside of it. The three main panels are
“Add/Hire Employee”, “Employee”, and “Salary Calculation”. The “Add/Hire employee”
contains one main panel and two nested panels that is added into the main panel, the “Employee”
panel and the “Salary Calculation” panel are both 2D panels nested inside one main panel
making it 3D panel, the reason for this is to dynamically reallocate the components inside each
panel, different layout managers were used for each panel such as a “null” layout manager for
the admin control GUI which mean no layout manager was used thus the bounds had to be set
manually for the two main panels as well as the “LogOut” button at the end of the page. Where,
inside the “Add/Hire employee” panel, a grid layout manager was used with specified number
of rows and columns.
For the second panel, a grid layout manager was used with 2 rows count and 1 column
count to add both “Employee” and “Salary Calculation” panels each of which have different
layout managers, while “Employee” panel has “null” layout manager since 2 panels are nested
inside of it each of which use Grid layout manager. For “Salary Calculation” panel, a Grid
layout manager was used as the components can be inserted in rows and columns and some do
correspond to other components. Figure 2.3 shows the example of nested panel.

Figure 2.3 shows the main panel and nested panels added into main panel

9
2.2.2 Buttons Listener and Database

Add/Hire Button
When the button is clicked, the name, profession, date of join, bank name, bank account,
and IC for the employee that has been entered by the user would be added into mySQL database.
After the addition of the employee, the user still would be in the same GUI so he or she could
add another employee to the database by entering the details of the other employee into the
GUI.
else if (e.getSource() == hireButton) {
boolean valid_name = false, valid_date = false, valid_bank=
boolean false,valid_ic = false;
boolean success = true;
String str_emp_name = empnameTextInput.getText().toString();
String str_dateOfJoin_output = dateOfJoinTextInput.getText().toString();
String str_bank_acc_Output = bankAccountTextInput.getText().toString();
String str_ic_passport_Output = passportTextInput.getText().toString();

try {
try{
Date date_dateofjoin = Date.valueOf(str_dateOfJoin_output);
valid_date = true;
}catch(Exception ex){
JOptionPane.showMessageDialog(hireButton, "The date format is wrong");
valid_date = false;
}
try{
Long long_bank_acc = Long.parseLong(str_bank_acc_Output);
if((str_bank_acc_Output.length() <10)
|| (str_bank_acc_Output.length()>14)){
JOptionPane.showMessageDialog(hireButton, "Enter a bank account number
between 10 digits to 14 digits");
valid_bank = false;
}
else
valid_bank= true;
}catch(Exception ex){
JOptionPane.showMessageDialog(hireButton, "Type a number in the bank
account");
valid_bank = false;
}

try{
Long long_ic_passport = Long.parseLong(str_ic_passport_Output);
valid_ic = true;
}catch(Exception ex){
JOptionPane.showMessageDialog(hireButton, "Type a number in the Passport
or IC");
valid_ic = false;
}

10
The code above shows the inside of the ActionListener of hirebutton where there is the
validation of the value keyed in by the user before it was added to the database. We first
declared the variable for retrieving the data from each text field and the initial validation of the
value into false. Then we created a try-catch block for each value, where inside we see the use
built in method named parseLong() and valueOf() for confirmation of the value is a Long or
Date datatype. If the method could be executed, it would change the validation variable into
true, which is important for later.
……
char[] check_name = str_emp_name.toCharArray();

for (char a : check_name) {


if (Character.isDigit(a)) {
valid_name = false;
}else
valid_name = true;
}
if(valid_name == false){
JOptionPane.showMessageDialog(hireButton, "Please type a string for
your name");
}

Continuing the verification, the code above displays on how to check if there is a integer
in the name, the input of the text is stored into an array and with the usage of for-each loop, it
iterate the loop and same as before, if there is no integer it would not set the validation into
true.
try{
if (valid_name == true && valid_date == true &&
valid_bank == true && valid_ic == true) {
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to
continue this operation?","Add Employee", JOptionPane.YES_NO_OPTION);
if(result== JOptionPane.YES_OPTION) {
success = db.add_employee(str_emp_name, profession_type,date_dateofjoin ,
name_of_bank ,bank_acc, ic);
if (success) {
System.out.println("success");
ResultSet rs = db.show_ID(ic);

if(rs.next()) {
int sql_id = rs.getInt("id");
String display_id = Integer.toString(sql_id);

JOptionPane.showMessageDialog(hireButton, "Successful Added Employee! ID:


"+ display_id);
empnameTextInput.setText("");
dateOfJoinTextInput.setText("");
bankAccountTextInput.setText("");
passportTextInput.setText("");
}
}
else
throw new Exception(); 11
}
else
JOptionPane.showMessageDialog(frame, "Operation Cancel");
}
}catch(Exception ex){
JOptionPane.showMessageDialog(hireButton, "Error connecting to mySQL");
}

catch(Exception ex){

}
}

After every verification has passed the test, the validation variables will all has been set to
true, so only then the code on adding the employee details to the database could be executed.
However, the user would be asked if he or she wants to continue with the operation first, if they
cancel then they would still go back to the GUI, but if they click yes it would call for the
add_employee() method, as seen in the code below, and the converted input of the user is put
inside the parameter to be added into mySQL. Next, if the data could be added, it would display
a message that its successful and the textfield in the GUI is emptied.

public boolean add_employee(String str_empname, String str_profession, Date


str_dateOfJoin_output, String bank_name, long
bankAcc, long ic_passport) {
try {
Connection connect = connection();
query = "INSERT INTO employee(name, profession, date_of_join,
Bank_name, bank_account, ic_passport)
VALUES(?,?,?,?,?,?)";

PreparedStatement preparestmt = connect.prepareStatement(query);


preparestmt.setString(1, str_empname);
preparestmt.setString(2, str_profession);
preparestmt.setDate(3, str_dateOfJoin_output);
preparestmt.setString(4, bank_name);
preparestmt.setLong(5, bankAcc);
preparestmt.setLong(6, ic_passport);
preparestmt.addBatch();
preparestmt.executeBatch();
connect.close();
return true;
}
catch(Exception ex) {
System.err.print("Got an exception!");
System.err.println(ex.getMessage());
set_errormessage(ex.getMessage());
return false;
}
}

12
In the previous salary button, we have used the prepareStatement method, which is setInt,
however now we used the setString, setLong, setDouble depending on the datatype that it is
declared inside of the method parameter which we can see from the code above. Then each
statement would be added into a batch using addBatch() method, in other words it would store
the records of the parameter from the textfield. Then we execute all the statement that we have
grouped together by executeBatch() to update the data to the database. The query we used
declaring the table name we are inserting to with INSERT INTO employee. Then inside the
first bracket we input the names of the column that we want to insert the data, while the second
bracket is the value of what we want to put inside. Figure 2.4 shows the output inside the
employee table in the database using MySQL Workbench after adding several employees using
the Employee Payroll Management System.

Figure 2.4 shows the display of employee table in the database using MySQL Workbench

Search Button
By clicking search button, the GUI shall generate employee name, profession, and date of
joining in the same GUI. If the searched employee is not the targeted employee, the admin will
just enter another employee ID number and click search button again to search for the new ID
number. Now, let us look into depth on the coding part. Figure 2.4 shows the result of search
button action.

Figure 2.4 shows the result of search button action

13
else if (e.getSource() == searchButton) {
try {
int valid_id = Integer.parseInt(id);
ResultSet result = db.search_employee(valid_id);
if (result.next()) {
String Name_out = result.getString("Employee_name");
displaynametext.setText(Name_out);
String profession_out = result.getString("profession");
displayproftext.setText(profession_out);
String date_out = result.getDate("date_of_join").toString();
displaydatetext.setText(date_out);
}
else
JOptionPane.showMessageDialog(searchButton, "No employee found!
Please ensure your ID is correct!");
} catch (NumberFormatException | SQLException ex) {
JOptionPane.showMessageDialog(searchButton, "Wrong Input");
}
}

In the above action performed by searchButton, we can see that we use database class’s
method which is ‘search_employee’ method. This method is defined in database class and
return instance of ResultSet. Following code show the definition of ‘search_employee’ method:
public ResultSet search_employee(int id) {
try
{
Connection connect = connection();
query = "SELECT Employee_name, Profession, date_of_join FROM employee WHERE
Employee_id = ?";
PreparedStatement preparestmt = connect.prepareStatement(query);
preparestmt.setInt(1, id);
output_db = preparestmt.executeQuery();
return output_db;
}
catch(Exception ex)
{
System.err.print("Got an exception!");
System.err.println(ex.getMessage());
return null;
}
}

In the search_employee method, it is similar to the ‘search_employee_salaryslip’ method


that we discussed early. The only different is the ‘query’ as this is to SELECT name, profession,
and date of join of the employee from the database’s table. Then the result of the query will be
stored in output_db and returned to the searchButton’s action.

14
In the searchButton’s action, if the employee exists in the database, it will display the
employee’s information by using setText method in the Java Swing component. It is used to
set the text of the label or text field, depend on which component we used to carry out the
programming. Another interesting and convenient built-in method is getString and getDate.
These two methods are built-in method of ResultSet that help us to get the data from the table.
If the value in the table is set as String, then we should use getString, while if the value is set
as Date format, then we should use getDate. There are many other methods associate with the
value that is set in the table, for example:

• getDouble
• getInt
• getFloat

If the employee data is not in the database, then it will proceed to else statement which is
displaying “Employee Not Found” message to the user.

Fire Button
In the same textfield for the search button, if the user needs to remove an employee an
employee from the database, he or she shall type the employee ID that they want to remove
and click the fire button. The user could decide if they want to remove the employee straight
away or if he wants to search for the employees’ details first then remove them.
else if (e.getSource() == fireButton) {
{ boolean success = false;
try {
int valid_id = Integer.parseInt(id);
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you
want to continue this operation (Employee ID: "+
valid_id + ")?","Remove Employee", JOptionPane.YES_NO_OPTION);
if(result== JOptionPane.YES_OPTION) {
success = db.delete_employee(valid_id);
if(success == true)
{
JOptionPane.showMessageDialog(fireButton, "Successfully Removed");
employeeIDTextInput.setText("");
displaynametext.setText("");
displayproftext.setText("");
displaydatetext.setText("");
}
else
throw new IllegalArgumentException();
}
else
JOptionPane.showMessageDialog(frame, "Operation Cancel");

} catch (IllegalArgumentException ex) {


JOptionPane.showMessageDialog(fireButton, "Wrong inputs!");
}
}
}

15
Above in the action performed for fire button, it would ask for the user confirmation if
they wanted to delete this employee. If they click yes, the delete_employee() method inside the
Database class is used. Then the same thing as the add/hire button, it would check if the
employee has been removed from the database, if it succeed then it would display a message
to the user if that employee has been deleted, then the Employee ID textfield and search display
of the employee is emptied. The subsequent code is for the delete_employee() method :

public boolean delete_employee(int id) {


try {
Connection connect = connection();
ResultSet rs = search_employee(id);
if(rs.next())
{
query = "DELETE FROM employee WHERE id = " + id;
statement = connect.createStatement();
return true;
}
else
return false;
}
catch (Exception ex)
{
System.err.print("Got an exception!");
System.err.println(ex.getMessage());
return false;
}
}

The same as our search button we also use the search_employee to check if the employee
the employee is inside the database. However, rather than displaying the result, we want to
delete the employee. So now the query inside the delete_employee method is purposed to delete
the row by finding the table name with DELETE FROM employee and the row that we want
to delete is set by the ID of our employee that has been made automatically by mySQL with
WHERE id =” + id. with the id being the one that has been entered by the user and it will be
given inside of the parameter of this method. Then using the statement interface method
createStatement() it is to create an object that will generate ResultSet with our id type and send
the statement we created into mySQL. The difference between Statement and PrepareStatement
is Statement is normally used for basic commands and cannot take in parameters. It is mainly
used for static SQL and if we want to run the query only once.

16
Update Salary Button
If user wishes to update the employee’s salary, he or she shall go to the salary calculation
to enter the duration of days and the amount of rate per day according to employee’s profession.
The salary will be calculated by the program and save into the database as basic salary.
Following code show the method definition in database class on calculating the basic salary
based on the days and rate given by user and update to the database:

public boolean update_salary(int days, double rate, int id) {


double salary = days*rate;
try {
Connection connect = connection();
ResultSet rs = search_employee(id);
if(rs.next()) {
query = "UPDATE employee SET salary = ? WHERE Employee_id = ?";
PreparedStatement preparestmt = connect.prepareStatement(query);
preparestmt.setDouble(1,salary);
preparestmt.setInt(2, id);
preparestmt.executeUpdate();
return true;
}
else
{
return false;
}
}
catch(Exception ex) {
System.err.println("Got an exception! ");
System.err.println(ex.getMessage());
return false;
}
}

In the update_salary method, it invokes another method as well which is ‘search_employee’


method. This is to ensure the employee’s ID that entered by the user is in the database. Then
use the if-else-then logic to check the output of the ResultSet. If user wishes to add bonus only
then the same method name will be used but accept different parameters and consists of
different definition.
public boolean update_salary(double bonus, int id) {
try {
Connection connect = connection();
ResultSet rs = search_employee(id);
if(rs.next()) {
query = "UPDATE employee SET bonus = ? WHERE Employee_id = ?";
… …

17
Above code shows the different ‘query’ depend on which user wishes to perform under
the same method name. Following show another query if user wishes to update the basic salary
and bonus as well:

query = "UPDATE employee SET salary = ?, bonus = ? WHERE Employee_id = ?";

In the actionPerformed method for setSalary button, first we need to declare few variables
to retrieve data from the text field that user entered, and Boolean data type to check validate
text field whether it is empty or not.

boolean success = false;


String days_output = salaryDaysTextInput.getText().toString();
String rate_output = salaryRateTextInput.getText().toString();
String bonus_output = bonusTextInput.getText().toString();
boolean empty_bonus = bonus_output.isEmpty();
boolean empty_days = days_output.isEmpty();
boolean empty_rate = rate_output.isEmpty();
boolean empty_id = id.isEmpty();

Above code shows the variable that we declared to retrieve the data from text field and use
Boolean to determine whether it is empty or not.

try
{
double valid_bonus = Double.parseDouble(bonus_output);
int valid_id = Integer.parseInt(id);
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want
to continue this operation (Employee ID: "+ valid_id + ")?",
"Set Salary", JOptionPane.YES_NO_OPTION);
if(result== JOptionPane.YES_OPTION)
{
success = db.update_salary(valid_bonus, valid_id);
if(success)
{
JOptionPane.showMessageDialog(setSalaryButton, "Successful
Update Salary");
employeeIDTextInput.setText("");
displaynametext.setText("");
displayproftext.setText("");
displaydatetext.setText("");
bonusTextInput.setText("");
}
else
JOptionPane.showMessageDialog(setSalaryButton, "Employee not
found! Please ensure your ID is correct!");}
else
JOptionPane.showMessageDialog(frame, "Operation Cancel");
}
catch(NumberFormatException ex)
JOptionPane.showMessageDialog(setSalaryButton, "Wrong inputs at
bonus!");
}

18
Above code shows the fragment of code inside the action performed by update salary
button where we use if-else-then logic to decide which method to be invoked. This can be done
by declaring methods with same name but different signatures using method overloading.

Log Out Button


Once user has completed the administrative task that he or she wishes to perform, the user
can click the log out button and go back to the LoginGUI. Following code show the action
performed by log out button in codes:

else if (e.getSource() == logOutButton) {


frame.dispose();
JOptionPane.showMessageDialog(logOutButton, "Good Bye! Thank you");
gui = new LoginGUI();
}

2.2.3 Exception Handling

Add/Hire Button
There are several exceptions that is needed to be caught mainly during the verification
process. There is also when we need to catch when mySQL could not connect. Succeeding
events are caught to display the error to the user.

• Character is entered in the bank account and IC


• Date is not according to YYY-MM-DD format
• The method add_employee() did not succeed in connecting to mySQL

As explained before, we use a built in method named parseLong() for bank account and
IC and valueOf() for date to see if the input is correct. If the input is wrong there there would
be an error on reading the value, and it would catch the error and display the message on where
the user put in the wrong input.

If the success variable that we stored our method for add_employee() it would catch the
error on the connection method declared inside the Database class. If the url, username, or
password was wrong it would catch it and display an error message of "Error connecting to
mySQL" to the user after he or she clicked the button.

Search Button
The exception handling in search button is similar to Generate Salary Button. We need to
ensure the ID entered by user must be only consists of Integer or numbers. Thus, parseInt
19
method is used here again as well in the try block, while catch block is to catch Number Format
Exception error.
Fire Button
The same as search button we want to check if the user has input the right value of only
Integers, so parseInt() was used. If there is a character inside it would catch the error and display
a message to the user. It would also check if the id that the user key in is inside the database
with the search_employee(), only then it can delete the employee.

Update Salary Button


To ensure the user entered value in Days, Rate, and Bonus text field are containing Integer
or numbers only, they are cast to their respective value to ensure unwanted value being stored
into the database or unwanted events to occur such as crashing of program. Is is similar to
Generate Salary Button as well.

2.3 Salary Slip GUI

2.3.1 Layout

Salary Slip is another GUI (Graphical User Interface) that we generated in our project.
Inside the slip, employee name and id are stated clearly. Basic salary of the employees is based
on their position in the organization, every profession has different basic salary. Moreover,
medical allowance, bonus, and tax deduction will also be stated clearly in the salary slip. After
carried out addition of medical allowance, bonus and basic salary, and tax deduction, the
system will calculate the net salary and display the values in the slip.

JLabel is used in coding salary slip layout. It is used to displays text in the GUI. The text fonts
and bounds could also be set. Besides, JPanel has also been used to set various layouts which
provide better organization of components. Figure 2.5 shows the coding of salary slip layout
and figure 2.6 shows the design of salary slip GUI.

20
Figure 2.5 shows the coding of salary slip layout

Figure 2.6 shows the design of salary slip layout

2.3.2 Buttons Listener

Bank Button
After user views his or her salary slip and wishes to go back to Login Page, the user can
click the back button. Following code shows the action performed by back button in codes:

if (e.getSource() == backbutton) {
dispose();

21
gui = new LoginGUI();
JOptionPane.showMessageDialog(backbutton, "Thank You! GoodBye!");

The ‘dispose()’ is to tell the program to dispose the current frame after user click the
back button, and the goodbye message will be displayed to user.

Print Button
In the event of user wishes to print his or her salary slip, the user can click the print button
and the program will print the salary slip to pdf format. This can be done by using PrinterJob
class in Java and override the print method in the class. The PageFormat in the parameter is
used to describe the page orientation and its size; while the page parameter is it is zero-based.
Since we only have one GUI, thus the page cannot be larger than zero. Following shows the
method definition:

@Override
public int print(Graphics graphics, PageFormat pdf, int page) throws
PrinterException
{
if (page > 0)
{
return NO_SUCH_PAGE;
}
Graphics2D graphics2d = (Graphics2D) graphics;
graphics2d.translate(pdf.getImageableX(), pdf.getImageableY());
graphics2d.scale(1.5, 1.5);
contentPanel.paint(graphics2d);
return PAGE_EXISTS;
}

2.3.3 Exception Handling

Print Button
To ensure the program will not crash if unwanted events happened, the print method
discussed previously are all located in the try block. In the event of unwanted situation
happened, the try-catch block will catch any printing related error condition with the help of
PrintException class.

22
CHAPTER 3: SUMMARY

The GUI was designed to be simple, yet professional. The variety of panels and nested
panels used as well as distinct layout managers for panels were designed to eliminate any visual
discomfort caused by scruffy design.

Buttons were named according to its label, generate button will generate employee salary slip
based on the ID entered, some buttons functions can access and edit database such as: Hire,
Fire and set salary buttons. Where search button is only going to search through database
elements ID, logout button is simple where is disposes the administrative GUI frame and
lunches the main GUI again.

Various human errors were considered during the design process, but the most effective way
to handle those errors is to prevent it from occurring. Thus, our payroll system applies
exception handling as well as checking inputs to ensure that entered inputs are less likely to
cause system errors, however, in the case of those errors occurrence, the system is able to
handle it using multiple exception handling mechanisms. In addition to that, the system is able
to display a pop-up message for the user describing the error that has occurred, so the user is
able to detect his input error or lack of specific input such as: the Employee ID in search panel.

MYSQL was used to design the database as it provides a dynamic database handling as well
as different functions to manipulate the data. Once the database is connected to the system, the
user shall be able to add, fire, search and use the system to its maximum capability, MYSQL
is also applying dynamic properties to avoid storage problems or database extend needs.

23

You might also like