Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help with this java program using GUI. Starter code provided at bottom. Emp

ID: 3575566 • Letter: N

Question

Need help with this java program using GUI. Starter code provided at bottom.

EmployeeFrame

EmployeeFrame extends JFrame
-   em : EmployeeManager
-   employeeTypeCombo : JComboBox<String>
-   firstField : JTextField
-   lastField : JTextField
-   middleCombo : JComboBox<Character>
-   genderCombo : JComboBox<Character>
-   employeeNumberField : JTextField
-   fullTimeRadio : JRadioButton
-   partTimeRadio : JRadioButton
-   amountField : JTextField
-   addEmployeeButton : JButton
-   employeeNumberRemoveField : JTextField
-   removeButton : JButton
-   employeeNumberUpdateField : JTextField
-   amountUpdateField : JTextField
-   updateHourlyButton : JButton
-   updateCommissionButton : JButton
-   updateFromFileButton : JButton
-   payoutButton : JButton
-   bonusButton : JButton
-   raisesButton : JButton
-   resetWeekButton : JButton
-   viewRequestButton : JButton
-   addRequestButton : JButton
-   grantRequestButton : JButton
-   sortPrintButton : JButton
-   printHourlyButton : JButton
-   printSalaryButton : JButton
-   printCommissionButton : JButton
-   findButton : JButton
-   exitButton : JButton
-   console : JTextArea
<<constructor>> EmployeeFrame()
-   createMiddleOptions() : Character[]

The EmployeeFrame has the following private inner class. This inner class will be the Event Handler for all of the EmployeeFrame’s buttons. Only the JButtons of the EmployeeFrame need a listener, no other components have a listener.

ButtonHandler implements ActionListener

+ actionPerformed(event : ActionEvent)
Starter code has been provided. This declares all of the data members, gives you the createMiddleOptions method (Used to quickly create an array of Characters A-Z for the middle initial Combo Box, and the set up of the JTextArea console.

Constructor
Sets up the Frame and creates all components. Creates the EmployeManager object the application will be manipulating. As you can see above, the Frame is logically split up into sections using panels. For each of these sections create a JPanel, set its Layout to a Flow Layout and give it a black boarder. This can be done like this:
       JPanel addPanel = new JPanel();
       addPanel.setLayout(new FlowLayout());
       addPanel.setBorder(BorderFactory.createLineBorder(Color.black));

Then create all of the components for that panel and add them to the panel in the order in which they appear, then add the panel to the Frame. Get your application to look as close to the example as possible noting the following JTextField sizes below as well as the default text.

JTextField Sizes
Name fields: 15
Employee Number fields: 5
Amount fields: 10

The Full/Part JRadioButtons belong to a ButtonGroup to ensure only one is selected at one time.

Also note that each section has a JLabel as the first component, do not forget to create and add these as well. They are not class wide data members since they do not need to be further referenced by us. We need access to the other components in the handler, so those are class wide.

Once all of the components have been created and added, attempt to call upon the EmployeeManager’s loadEmployees with the file name, “employees.ser” and “requests.dat”. If successful output “Employees Loaded” to the console, otherwise “Employees Not Loaded”

Notes on JTextArea console
Whenever you perform an action that causes the console to be updated clear the previous contents to avoid clutter. These two JTextArea methods will be helpful for manipulating the console:

public void setText(String t)
Sets the text of the JTextArea to the passed String, removing the current contents.

Public void append(String t)
Appends the passed String to the current contents of the JTextArea.
ButtonHandler
Your EmployeeFrame constructor only needs to create ONE instance of the ButtonHandler, since the same Handler will be capable of handling all buttons. Add the same handler to all JButton components.

Note on input components
Some of the operations require altering the contents of one or more of the JTextFields, JComboBoxes, and/or JRadioButtons. Once the action has occurred reset the associated components to their starting values. For example, the user enters all of the information for a new Employee and hits the “Add Employee” button. Whether or not it was successful set all of the components back. firstField is set back to the String, “First”, lastField to, “Last”, middleCombo to ‘A’, genderCombo to ‘M’, etc.

Following is what should happen if the JButtons are pressed. These actions go in the ButtonHandler’s actionPerformed() method as demonstrated in class. First determine which button triggered the event by using the event’s getSource() method, then perform the correct actions for that button.

addEmployeeButton
Using the user inputs from the Add Employee section, call upon the EmployeeManager’s addEmployee. If the Employee is added successfully output “Employee Added” to the console. If either an InvalidEmployeeNumberException or NumberFormatException occurs output “Invalid Employee Number to the console. Reset the user inputs back to defaults.

removeButton
Attempt to remove the Employee given in the section. If successful output, “Employee (EmployeeNumber) Removed”. If the Employee does not exist or a NumberFormatException occurs output “No Such Employee”. Reset the Employee number field.

updateHourlyButton/updateCommissionButton
Using the values in the Employee number and amount field attempt to call upon the increaseHours/increaseSales method. If a NumberFormatException occurs in parsing the Employee number or amount output “Invalid Employee Number” or “Invalid Amount”, respectively. If the Employee does not exist output “No Such Employee”. If the call to increaseHours/increaseSales returns false, this means the index passed is not to the correct type of Employee, output that information to the console as either, “Employee Not Hourly” or “Employee Not Commission”, respectively.
If the action is successful output one of the following depending on the button pressed, “(Employee Number) increased by (Amount) hours” or “(Employee Number) increased by (Amount) sales”. The amount should be formatted to show exactly 2 decimal points.

updateFromFileButton
To choose the file to use we will use the JFileChooser, the majority of the code is provided here:

JFileChooser fileChooser = new JFileChooser(new File("."));
               int fileRet = fileChooser.showOpenDialog(null);
  
               if(fileRet == JFileChooser.APPROVE_OPTION)
               {
                   if(em.processUpdates(fileChooser.getSelectedFile().getAbsolutePath()))
                   {
                       //Output "Updates Processed Successfully" to console
                   }
                   else
                   {
                       //Output "Updates Not Processed" to console
                   }
               }
payoutButton
Using EmployeeManager’s calculatePayout() output the payout to the console in the format, “Total weekly payout is (Amount)”

bonusButton
Using EmployeeManager’s holidayBonuses() output the bonus amount to the console in the format, “Total holiday bonus is (Amount)”

raisesButton
Applies the EmployeeManager’s annualRaises() and outputs “Annual Raises Applied”.

resetWeekButton
Applies the EmployeeManager’s resetWeek() and outputs “Weekly values reset”.

viewRequestButton
Outputs the String returned by EmployeeManager’s outputRequests to the console. If there is a non-null Next Request output it to the console as well in the format, “(Employee) will receive next request”

addRequestButton
Prompt user for an Employee number using JOptionPane’s showInputDialog with the text “Enter Employee Number”

Attempts to add Employee with the given number to the vacation Queue. If a NumberFormatException occurs when parsing the input output “Invalid Employee Number to the console. If the Employee does not exist output “No Such Employee” to the console. If the action is successful output “Employee (Employee Number) added to vacation queue” to the console.

grantRequestButton
Attempt to grant next vacation request. If there is no Employee in the Queue output “No vacation requests” to console, if it succeeds output “(Employee) granted vacation request”

sortPrintButton
Sort the Employees using the EmployeeManager’s sort() then output all Employees to the console.

printHourlyButton/printSalaryButton/printCommissionButton
Output the appropriate Employees to the console.

findButton
Prompt user for a search String using JOptionPane’s showInputDialog with the text “Enter Search String”

If nothing is entered do not try to search. If a String is entered us EmployeeManager’s findAllBySubstring() to output matches to the console. If an InvalidCharacterException is thrown output “Invalid character found in search” to the console.

exitButton
Call EmployeeManager’s saveEmployees with the files “employees.ser” and “requests.dat” and terminate the program by calling System.exit(0)

___________________________________________________________________________________________________________________________________

Explanation / Answer


// This program creates GUI.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.Font;
//Imports go here

public class EmployeeFrame extends JFrame
{
   private EmployeeManager em;
  
   //Components for Adding Employee
   private JComboBox<String> employeeTypeCombo;
   private JTextField firstField;
   private JTextField lastField;
   private JComboBox<Character> middleCombo;
   private JComboBox<Character> genderCombo;
   private JTextField employeeNumberField;
   private JRadioButton fullTimeRadio;
   private JRadioButton partTimeRadio;
   private JTextField amountField;
   private JButton addEmployeeButton;
  
   //Components for Remove Employee
   private JTextField employeeNumberRemoveField;
   private JButton removeButton;
  
   //Components for Updating Employee
   private JTextField employeeNumberUpdateField;
   private JTextField amountUpdateField;
   private JButton updateHourlyButton;
   private JButton updateCommissionButton;
   private JButton updateFromFileButton;
  
   //Components for Financial Options
   private JButton payoutButton;
   private JButton bonusButton;
   private JButton raisesButton;
   private JButton resetWeekButton;
  
   //Components for Vacation Request
   private JButton viewRequestButton;
   private JButton addRequestButton;
   private JButton grantRequestButton;
  
   //Management Panel
   private JButton sortPrintButton;
   private JButton printHourlyButton;
   private JButton printSalaryButton;
   private JButton printCommissionButton;
   private JButton findButton;
   private JButton exitButton;
  
   private JTextArea console;
  
   public EmployeeFrame()
   {
       JFrame frame = new JFrame("Input");
      
       JLabel label1, label2, label3, label4, label5, label6;
       String[] gender = {"M","F"};
       String[] type = {"Hourly","Salary","Commission"};
       String[] middleI = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
                           "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
      
       super("Employee Manager");
       setLayout(new FlowLayout());
      
       //Create EmployeeManager
       em = new EmployeeManager();
       EmployeeFrame ef = new EmployeeFrame(em);

      
       //Create ButtonHandler
       ButtonHandler bh = new ButtonHandler();
      
       addEmployeeButton = new Button(“Add Employee”);
       removeButton = new Button(“Remove Employee”);
       updateHourlyButton = new Button(“Update Hourly Employee”);
       updateCommissionButton = new Button(“Update Commission Employee”);
       updateFromFileButton = new Button(“Update From File”);
       payoutButton = new Button(“Payout”);
       bonusButton = new Button(“Bonus”);
       raisesButton = new Button(“Raises”);
       resetWeekButton = new Button(“Reset Week”);
       viewRequestButton = new Button(“View Requests”;
       addRequestButton = new Button(“Add Requests”);
       grantRequestButton = new Button(“Grant Request”);
       sortPrintButton = new Button(“Sort Print”);
       printHourlyButton = new Button(“Print Hourly”);
       printSalaryButton = new Button(“Print Salary”);
       printCommissionButton = new Button(“Print Commission);
       findButton = new Button(“Find”);
       exitButton = new Button(“Exit”);

       addEmployeeButton.addActionListener(bh);
       removeButton.addActionListener(bh);
       updateHourlyButton.addActionListener(bh);
       updateCommissionButton.addActionListener(bh);
       updateFromFileButton.addActionListener(bh);
       payoutButton.addActionListener(bh);  
       bonusButton.addActionListener(bh);
       raisesButton.addActionLister(bh);
       resetWeekButton.addActionListener(bh);
       viewRequestButton.addActionListenerbh);
       addRequestButton.addActionListener(bh);
       grantRequestButton.addActionListener(bh);  
       sortPrintButton.addActionListener(bh);
       printHourlyButton.addActionListener(bh);
       printSalaryButton..addActionListener(bh);
       printCommissionButton..addActionListener(bh);
       findButton.addActionListener(bh);
       exitButton.addActionListener(bh);

  
       //ADD EMPLOYEE PANEL
       label1 = new JLabel("Add Employee:");
       JPanel employeePanel = new JPanel();
       employeePanel.setLayout(new FlowLayout());
       employeePanel.setBorder(BorderFactory.createLineBorder(Color.black));
       employeeTypeCombo = new JComboBox<String>(type,"Hourly")
       firstField = new JTextField("First",15);
       lastField = new JTextField("Last",15);
       middleCombo = new JComboBox<Character>("A",middleI);
       genderCombo = new JComboBox<Character>("M",gender);
       employeeNumberField = new JTextField("Emp#",5);
       fullTimeRadio = new JRadioButton(“Full-time”);
       partTimeRadio = new JRadioButton(“Part-time”);
       amountField = new JTextField("Wage/Salary/Rate",10);
       addEmployeeButton = new JButton(“Add Employee”);
       employeePanel.add(label1,employeeTypeCombo,firstField,lastfield,middleCombo,genderCombo,fullTimeRadio,partTimeRadio,amountField,employeeButton)
       add(employeePanel);

       //REMOVE EMPLOYEE PANEL
       label2 = new JLabel("Remove Employee:");
       JPanel removeEmpPanel = new JPanel();
       removeEmpPanel.setLayout(new FlowLayout());
       removeEmpPanel.setBorder(BorderFactory.createLineBorder(Color.black));
       employeeNumberRemoveField = new JTextField("Emp#",5);
       removeButton = new JButton(“Remove Button”);
       removeEmpPanel.add(label2,employeeNumberRemoveField, removeButton)
       add(removeEmpPanel);

       //UPDATE PANEL
       label3 = new JLabel("Update Employee:");
       JPanel updatePanel = new JPanel();
       updatePanel.setLayout(new FlowLayout());
       updatePanel.setBorder(BorderFactory.createLineBorder(Color.black));
       employeeNumberUpdateField = new JTextField("Emp#",5);
       amountUpdateField = new JTextField("Hours/Sales",10);
       updateHourlyButton = new JButton(“Update Hourly”);
       updateCommissionButton = new JButton(“Update Commission”);
       updateFromFileButton = new JButton(“Update From File”);
       updatePanel.add(label3,employeeNumberUpdateField,amountUpdateField,updateHourlyButton,updateCommissionButton, updateFromFileButton)
       add(updatePanel);      

       //FINANCIAL PANEL
       label4 = new JLabel("Financial Options:");
       JPanel financialPanel = new JPanel();
       financialPanel.setLayout(new FlowLayout());
       financialPanel.setBorder(BorderFactory.createLineBorder(Color.black));
       payoutButton = new JButton(“Payout”);
       bonusButton = new JButton(“Bonus”);
       raisesButton = new JButton(“Raises”);
       resetWeekButton = new JButton(“Reset Week”);
       financialPanel.add(label4,payoutButton,bonusButton,raisesButton,resetWeekButton)
       add(financialPanel);
      
       //VACATION PANEL
       label5 = new JLabel("Vacation Queue:");
       JPanel vacationPanel = new JPanel();
       vacationPanel.setLayout(new FlowLayout());
       vacationPanel.setBorder(BorderFactory.createLineBorder(Color.black));
       viewRequestButton = new JButton(“View Request”);
       addRequestButton = new JButton(“Add Request”);
       grantRequestButton = new JButton(“Grant Request”);
       vacationPanel.add(label5,viewRequestButton,grantRequestButton,addRequestButton)
       add(vacationPanel);

       //CONSOLE PANEL
       JPanel consolePanel = new JPanel();
       consolePanel.setLayout(new FlowLayout());
       console = new JTextArea(20, 100);
       console.setEditable(false);
       JScrollPane consoleScrollPane = new JScrollPane(console);
       consolePanel.add(consoleScrollPane);
       add(consolePanel);
      
       //Management PANEL
       label6 = new JLabel("Management:");
       JPanel managementPanel = new JPanel();
       managementPanel.setLayout(new FlowLayout());
       managementPanel.setBorder(BorderFactory.createLineBorder(Color.black));
       sortPrintButton = new JButton(“Sort”);
       printHourlyButton = new JButton(“Print Hourly”);
       printSalaryButton = new JButton(“Print Salary”);
       printCommissionButton = new JButton(“Print Commission”);
       findButton = new JButton(“Find”);
       exitButton = new JButton(“Exit”);
       managementPanel.add(label6,sortPrintButton,printHourlyButton,printSalaryButton,printCommissionButton,findButton,exitButton)
       add(managementPanel);

       if(em.loadEmployees("employees.ser", "requests.dat"))
           console.append("Employees Loaded ");
       else
           console.append("Employees Not Loaded ");
   }
  
   private Character[] createMiddleOptions()
   {
       Character[] ret = new Character[26];
       for(int i = 0; i < 26; i++)
           ret[i] = (char)(i+65);
      
       return ret;
   }
  
   //inner class for ActionListener
   private class ButtonHandler implements ActionListener
   {

       @Override
       public void actionPerformed(ActionEvent event)
       {
           //EVENT HANDLER CODE HERE
           if(event.getSource().equals(addEmployeeButton))
           {
               if (firstField.getText() == "" || lastField.getText() == "" || employeeNumberField.getText() < 10000 || employeeNumberField.getText() > 99999 || amountField.getText() == "")
               {
                   console.setText("Employee not added");
               }
              
               else
               {
                   try
                   {
                       em.addEmployee(firstField.getText(),lastField.getText(),middleCombo.getSelectedItem(),genderCombo.getSelectedItem(),employeeNumberField.getText(), fullTimeRadio.isSelected(),partTimeRadio.isSelected(), amountField.getText() );
                       console.setText("Employee Added");
                   }
                   catch(InvalidEmployeeNumberException iee)
                   {
                       console.setText("Invalid Employee Number");
                   }
                   catch (NumberFormatException nfe)
                   {
                       console.setText("Invalid Employee Number");
                   }
               }
               firstfield.setText("");
               lastField.setText("");
               middleCombo.setSelectedItem("");
               genderCombo.setSelectedItem("");
               employeeNumberField.setText("");
               amountField.setText("");
           }
          
           if(event.getSource().equals(removeButton))
           {
               if(employeeNumberField.getText() == "")
               {
                   console.setText("No Such Employee");
               }
              
               else
               {
                   try
                   {
                       em.removeEmployee(employeeNumberField.getText());
                   }
                   catch (NumberFormatException b)
                   {
                       console.setText("No Such Employee");
                   }
               }
               employeeNumberRemoveField.setText("");
           }
          
           if(event.getSource().equals(updateHourlyButton))
           {
               if(employeeNumberField.getText() == "")
               {
                   console.setText("No Such Employee");
               }
              
               try
               {
                   em.increaseHours(employeeNumberField.getText(),amountField.getText());
                  
                   console.setText("%s increased by %s.2f hours",employeeNumberField.getText(),amountField.getText());
               }
               catch(NumberFormatException nfE)
               {
                   if(employeeNumberField.getText() == "")
                   {
                       console.setText("Invalid Employee Number");
                   }
                   if(amountField.getText() == "")
                   {
                       console.setText("Invalid Amount");
                   }
               }
               if (em.increaseHours(employeeNumberField.getText(),amountField.getText()) == false)
               {
                   console.setText("Employee Not Hourly");
               }
           }
          
           if(event.getSource().equals(updateCommissionButton))
           {
               try
               {
                   em.increaseSales(employeeNumberField.getText(),amountField.getText());
                  
                   console.setText("%s increased by %s sales",employeeNumberField.getText(),amountField.getText());
               }
               catch(NumberFormatException nFEe)
               {
                   if(employeeNumberField.getText() == "")
                   {
                       console.setText("Invalid Employee Number");
                   }
                   if(amountField.getText() == "")
                   {
                       console.setText("Invalid Amount");
                   }
               }
              
               if (em.increaseSales(employeeNumberField.getText(),amountField.getText()) == false)
               {
                   console.setText("Employee Not Commission");
               }
           }
          
           if(event.getSource().equals(updateFromFileButton))
           {
               JFileChooser fileChooser = new JFileChooser(new File("."));
               int fileRet = fileChooser.showOpenDialog(null);
  
               if(fileRet == JFileChooser.APPROVE_OPTION)
               {
                   if(em.processUpdates(fileChooser.getSelectedFile().getAbsolutePath()))
                   {
                       //Output "Updates Processed Successfully" to console
                   }
                   else
                   {
                       //Output "Updates Not Processed" to console
                   }
               }
           }
          
           if(event.getSource().equals(payoutButton))
           {
               em.calculatePayout();
              
               console.setText("Total weekly payout is %s");
           }
          
           if(event.getSource().equals(bonusButton))
           {
               em.holidayBonuses();
              
               console.setText("Total holiday bonus is %s");
           }
          
           if(event.getSource().equals(raisesButton))
           {
               em.annualRaises();
              
               console.setText("Annual Raises Applied");
           }
          
           if(event.getSource().equals(resetWeekButton))
           {
               em.resetWeek();
              
               console.setText("Weekly values reset");
           }
          
           if(event.getSource().equals(viewRequestButton))
           {
               em.outputRequests();
              
               if
           }
          
           if(event.getSource().equals(addRequestButton))
           {
               int empN = JOptionPane.showInput(frame,"Enter Employee Number: ");
               try
               {
                   em.addRequest(empN);
                  
                   console.setText("“Employee %s added to vacation queue",employeeNumberField.getText());
               }
               catch(NumberFormatException nnfe)
               {
                   console.setText("Invalid Employee Number");
               }
               catch (InvalidEmployeeNumberException iene)
               {
                   console.setText("No Such Employee");
               }  
           }
          
           if(event.getSource().equals(grantRequestButton))
           {
               try
               {
                   em.grantRequest();
                  
                   console.setText("%s granted vacation request", employeeNumberField.getText());
               }
               catch(InvalidEmployeeNumberException ienee)
               {
                   console.setText("No vacation requests” to console");
               }
           }
          
           if(event.getSource().equals(sortPrintButton))
           {
               em.sort();
              
               console.setText(em.toString());
           }
          
           if(event.getSource().equals(printHourlyButton))
           {
               console.setText(em.listHourly());
           }
          
           if(event.getSource().equals(printSalaryButton))
           {
               console.setText(em.listSalary());
           }
          
           if(event.getSource().equals(printCommissionButton))
           {
               console.setText(em.listCommission());
           }
          
           if(event.getSource().equals(findButton))
           {
               String s = JOptionPane.showInput(frame,"Enter Search String: ");
              
               if(s == "")
               {}
               else
               {
                   try
                   {
                       em.findAllBySubstring(s);
                   }
                   catch(InvalidCharacterException ice)
                   {
                       console.setText("Invalid character found in search");
                   }
               }
           }
          
           if(event.getSource().equals(exitButton))
           {
               em.saveEmployees("employees.ser", "requests.dat");
               System.exit(0);
           }
          
       }
   }
}