Create Employee Form using Java

Write a Java program that can create an employee form for inserting the detail of employee in an organization by using Applets create a JFrame which have labels, text box, Radio button, Check Box, button etc.

Step-by-Step Process to Implement Java Applet with JFrame in VS Code

Step 1: Install Java Development Kit (JDK)

  1. Download and Install JDK: Ensure you have the Java Development Kit (JDK) installed on your system. You can download it from Oracle’s official website or OpenJDK.

  2. Set JAVA_HOME Environment Variable:

    • On Windows: Go to System Properties -> Advanced -> Environment Variables, add JAVA_HOME with the path to your JDK installation.
    • On Mac/Linux: Edit the ~/.bash_profile, ~/.zshrc, or ~/.bashrc file and add export JAVA_HOME=/path/to/jdk.
  3. Verify Installation: Open a terminal and run java -version and javac -version to ensure Java is installed correctly.

Step 2: Install Visual Studio Code and Java Extensions

  1. Download and Install VS Code: If you haven’t already, download and install Visual Studio Code from here.

  2. Install Java Extensions:

    • Open VS Code and go to the Extensions view by clicking on the square icon in the sidebar or pressing Ctrl+Shift+X.
    • Search for “Java Extension Pack” and install it. This pack includes essential extensions like:
      • Language Support for Java™ by Red Hat
      • Debugger for Java
      • Java Test Runner
      • Maven for Java
      • Visual Studio IntelliCode

Step 3: Create a New Java Project

  1. Open VS Code and create a new folder for your Java project.
  2. Open the folder in VS Code.
  3. Create a New Java File:
    • Click on File > New File or press Ctrl+N.
    • Save the file as EmployeeForm.java.

Step 4: Write the Java Program

Copy and paste the Java code provided earlier into EmployeeForm.java:

				
					import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EmployeeForm extends JApplet {
    private JTextField nameField, ageField, departmentField;
    private JRadioButton maleButton, femaleButton;
    private JCheckBox javaCheckBox, pythonCheckBox, cppCheckBox;
    private JButton submitButton, resetButton;
    
    @Override
    public void init() {
        // Set up the frame
        JFrame frame = new JFrame("Employee Form");
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(8, 2));  // 8 rows, 2 columns
        
        // Name Label and Text Field
        JLabel nameLabel = new JLabel("Name:");
        nameField = new JTextField();
        frame.add(nameLabel);
        frame.add(nameField);
        
        // Age Label and Text Field
        JLabel ageLabel = new JLabel("Age:");
        ageField = new JTextField();
        frame.add(ageLabel);
        frame.add(ageField);
        
        // Department Label and Text Field
        JLabel departmentLabel = new JLabel("Department:");
        departmentField = new JTextField();
        frame.add(departmentLabel);
        frame.add(departmentField);
        
        // Gender Label and Radio Buttons
        JLabel genderLabel = new JLabel("Gender:");
        maleButton = new JRadioButton("Male");
        femaleButton = new JRadioButton("Female");
        ButtonGroup genderGroup = new ButtonGroup();
        genderGroup.add(maleButton);
        genderGroup.add(femaleButton);
        JPanel genderPanel = new JPanel();
        genderPanel.add(maleButton);
        genderPanel.add(femaleButton);
        frame.add(genderLabel);
        frame.add(genderPanel);
        
        // Skills Label and Checkboxes
        JLabel skillsLabel = new JLabel("Skills:");
        javaCheckBox = new JCheckBox("Java");
        pythonCheckBox = new JCheckBox("Python");
        cppCheckBox = new JCheckBox("C++");
        JPanel skillsPanel = new JPanel();
        skillsPanel.add(javaCheckBox);
        skillsPanel.add(pythonCheckBox);
        skillsPanel.add(cppCheckBox);
        frame.add(skillsLabel);
        frame.add(skillsPanel);
        
        // Submit Button
        submitButton = new JButton("Submit");
        frame.add(submitButton);
        
        // Reset Button
        resetButton = new JButton("Reset");
        frame.add(resetButton);
        
        // Add Action Listeners
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String age = ageField.getText();
                String department = departmentField.getText();
                String gender = maleButton.isSelected() ? "Male" : "Female";
                String skills = "";
                if (javaCheckBox.isSelected()) skills += "Java ";
                if (pythonCheckBox.isSelected()) skills += "Python ";
                if (cppCheckBox.isSelected()) skills += "C++ ";
                
                // Show the details in a message dialog
                JOptionPane.showMessageDialog(frame, "Employee Details:\nName: " + name + "\nAge: " + age + "\nDepartment: " + department + "\nGender: " + gender + "\nSkills: " + skills);
            }
        });
        
        resetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Reset all fields
                nameField.setText("");
                ageField.setText("");
                departmentField.setText("");
                genderGroup.clearSelection();
                javaCheckBox.setSelected(false);
                pythonCheckBox.setSelected(false);
                cppCheckBox.setSelected(false);
            }
        });
        
        // Make the frame visible
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // Run the applet in a JFrame
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                EmployeeForm form = new EmployeeForm();
                form.init();
            }
        });
    }
}

				
			
Employee Form using JApplets Screenshot

Screenshot of the Output Form for the above code

If you get an error in the above code, that might be because of the version that you are using. In such case, use the code given below.

Step-by-Step Process to Implement Standard JFrame in VS Code

Instead of using JApplet, we can create a standard JFrame application that works as a standalone desktop application. Let’s modify the code to use JFrame directly, without extending JApplet.

Here is the revised version of the code using JFrame:

				
					import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EmployeeForm {
    private JTextField nameField, ageField, departmentField;
    private JRadioButton maleButton, femaleButton;
    private JCheckBox javaCheckBox, pythonCheckBox, cppCheckBox;
    private JButton submitButton, resetButton;

    public EmployeeForm() {
        // Set up the frame
        JFrame frame = new JFrame("Employee Form");
        frame.setSize(450, 550);  // Adjusted height to accommodate the form
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());  // Use BorderLayout

        // Heading at the top
        JLabel headingLabel = new JLabel("edSlash Coding Hub", JLabel.CENTER);
        headingLabel.setFont(new Font("Arial", Font.BOLD, 24));  // Set the font to bold and increase size
        headingLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));  // Add top and bottom padding
        frame.add(headingLabel, BorderLayout.NORTH);

        // Main panel with padding around the form
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));  // Add 15 pixels of padding around the form

        // Create a panel for the form inputs
        JPanel formPanel = new JPanel(new GridLayout(8, 2, 5, 5));  // 8 rows, 2 columns with 5px gaps
        
        // Name Label and Text Field
        JLabel nameLabel = new JLabel("Name:");
        nameField = new JTextField();
        formPanel.add(nameLabel);
        formPanel.add(nameField);
        
        // Age Label and Text Field
        JLabel ageLabel = new JLabel("Age:");
        ageField = new JTextField();
        formPanel.add(ageLabel);
        formPanel.add(ageField);
        
        // Department Label and Text Field
        JLabel departmentLabel = new JLabel("Department:");
        departmentField = new JTextField();
        formPanel.add(departmentLabel);
        formPanel.add(departmentField);
        
        // Gender Label and Radio Buttons
        JLabel genderLabel = new JLabel("Gender:");
        maleButton = new JRadioButton("Male");
        femaleButton = new JRadioButton("Female");
        ButtonGroup genderGroup = new ButtonGroup();
        genderGroup.add(maleButton);
        genderGroup.add(femaleButton);
        JPanel genderPanel = new JPanel();
        genderPanel.add(maleButton);
        genderPanel.add(femaleButton);
        formPanel.add(genderLabel);
        formPanel.add(genderPanel);
        
        // Skills Label and Checkboxes
        JLabel skillsLabel = new JLabel("Skills:");
        javaCheckBox = new JCheckBox("Java");
        pythonCheckBox = new JCheckBox("Python");
        cppCheckBox = new JCheckBox("C++");
        JPanel skillsPanel = new JPanel();
        skillsPanel.add(javaCheckBox);
        skillsPanel.add(pythonCheckBox);
        skillsPanel.add(cppCheckBox);
        formPanel.add(skillsLabel);
        formPanel.add(skillsPanel);
        
        // Submit Button
        submitButton = new JButton("Submit");
        formPanel.add(submitButton);
        
        // Reset Button
        resetButton = new JButton("Reset");
        formPanel.add(resetButton);

        // Add the form panel to the center
        mainPanel.add(formPanel, BorderLayout.CENTER);
        
        // Add Action Listeners
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String age = ageField.getText();
                String department = departmentField.getText();
                String gender = maleButton.isSelected() ? "Male" : "Female";
                String skills = "";
                if (javaCheckBox.isSelected()) skills += "Java ";
                if (pythonCheckBox.isSelected()) skills += "Python ";
                if (cppCheckBox.isSelected()) skills += "C++ ";
                
                // Show the details in a message dialog
                JOptionPane.showMessageDialog(frame, "Employee Details:\nName: " + name + "\nAge: " + age + "\nDepartment: " + department + "\nGender: " + gender + "\nSkills: " + skills);
            }
        });
        
        resetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Reset all fields
                nameField.setText("");
                ageField.setText("");
                departmentField.setText("");
                genderGroup.clearSelection();
                javaCheckBox.setSelected(false);
                pythonCheckBox.setSelected(false);
                cppCheckBox.setSelected(false);
            }
        });
        
        // Add the main panel to the frame
        frame.add(mainPanel, BorderLayout.CENTER);

        // Make the frame visible
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // Run the application
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new EmployeeForm(); // Create and show the EmployeeForm
            }
        });
    }
}

				
			

Step 5: Compile and Run the Java Program

  1. Compile the Program:

    • Open the terminal in VS Code by clicking on Terminal > New Terminal or pressing `Ctrl+“.
    • Run the following command to compile the Java program:
				
					javac EmployeeForm.java

				
			
  • This will compile your program and create a EmployeeForm.class file in the same directory.

  • Run the Program:

    • To run the Java program, use the following command:
				
					java EmployeeForm

				
			
Employee Form Screenshot

Screenshot of the Output Form for the above code

If everything is set up correctly, a new window will pop up with the Employee Form GUI.

  • Step 6: Test the GUI Application

    • Interact with the Form: Enter details like name, age, department, select gender, check skills, and click the Submit button to see a message dialog displaying the entered details.
    • Reset the Form: Click the Reset button to clear all fields.

    Step 7: Troubleshooting Common Issues

    • JDK Not Found: Ensure that the JAVA_HOME environment variable is set correctly.
    • Class Not Found Error: Make sure the file name matches the class name and you compile the file before running it.
    • GUI Not Displaying Properly: Make sure all necessary imports are included at the top of the Java file.

    Step 8: Save and Close

    • Save the changes and close the editor when you’re done.

Java Program to handle the events for checking the data input by user.

To handle events for checking the data input by the user, you need to validate each input field’s data before processing it. This involves adding checks to ensure that fields are not empty, age is a valid number, gender is selected, and at least one skill is chosen.

Below is the updated Java Swing program with input validation checks:

				
					import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EmployeeForm {
    private JTextField nameField, ageField, departmentField;
    private JRadioButton maleButton, femaleButton;
    private JCheckBox javaCheckBox, pythonCheckBox, cppCheckBox;
    private JButton submitButton, resetButton;

    public EmployeeForm() {
        // Set up the frame
        JFrame frame = new JFrame("Employee Form");
        frame.setSize(450, 550);  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());  

        // Heading at the top
        JLabel headingLabel = new JLabel("edSlash Coding Hub", JLabel.CENTER);
        headingLabel.setFont(new Font("Arial", Font.BOLD, 24));  
        headingLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));  
        frame.add(headingLabel, BorderLayout.NORTH);

        // Main panel with padding around the form
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));  

        // Create a panel for the form inputs
        JPanel formPanel = new JPanel(new GridLayout(8, 2, 5, 5));  

        // Name Label and Text Field
        JLabel nameLabel = new JLabel("Name:");
        nameField = new JTextField();
        formPanel.add(nameLabel);
        formPanel.add(nameField);

        // Age Label and Text Field
        JLabel ageLabel = new JLabel("Age:");
        ageField = new JTextField();
        formPanel.add(ageLabel);
        formPanel.add(ageField);

        // Department Label and Text Field
        JLabel departmentLabel = new JLabel("Department:");
        departmentField = new JTextField();
        formPanel.add(departmentLabel);
        formPanel.add(departmentField);

        // Gender Label and Radio Buttons
        JLabel genderLabel = new JLabel("Gender:");
        maleButton = new JRadioButton("Male");
        femaleButton = new JRadioButton("Female");
        ButtonGroup genderGroup = new ButtonGroup();
        genderGroup.add(maleButton);
        genderGroup.add(femaleButton);
        JPanel genderPanel = new JPanel();
        genderPanel.add(maleButton);
        genderPanel.add(femaleButton);
        formPanel.add(genderLabel);
        formPanel.add(genderPanel);

        // Skills Label and Checkboxes
        JLabel skillsLabel = new JLabel("Skills:");
        javaCheckBox = new JCheckBox("Java");
        pythonCheckBox = new JCheckBox("Python");
        cppCheckBox = new JCheckBox("C++");
        JPanel skillsPanel = new JPanel();
        skillsPanel.add(javaCheckBox);
        skillsPanel.add(pythonCheckBox);
        skillsPanel.add(cppCheckBox);
        formPanel.add(skillsLabel);
        formPanel.add(skillsPanel);

        // Submit Button
        submitButton = new JButton("Submit");
        formPanel.add(submitButton);

        // Reset Button
        resetButton = new JButton("Reset");
        formPanel.add(resetButton);

        // Add the form panel to the center
        mainPanel.add(formPanel, BorderLayout.CENTER);

        // Add Action Listeners
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleSubmitAction(frame);
            }
        });

        resetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleResetAction();
            }
        });

        // Add the main panel to the frame
        frame.add(mainPanel, BorderLayout.CENTER);

        // Make the frame visible
        frame.setVisible(true);
    }

    private void handleSubmitAction(JFrame frame) {
        String name = nameField.getText().trim();
        String ageText = ageField.getText().trim();
        String department = departmentField.getText().trim();
        String gender = "";

        // Validate Name
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "Please enter the name.", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Validate Age
        int age;
        try {
            age = Integer.parseInt(ageText);
            if (age <= 0) {
                throw new NumberFormatException("Age must be positive.");
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(frame, "Please enter a valid age (positive integer).", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Validate Department
        if (department.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "Please enter the department.", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Validate Gender
        if (maleButton.isSelected()) {
            gender = "Male";
        } else if (femaleButton.isSelected()) {
            gender = "Female";
        } else {
            JOptionPane.showMessageDialog(frame, "Please select a gender.", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Collect Skills
        StringBuilder skills = new StringBuilder();
        if (javaCheckBox.isSelected()) skills.append("Java ");
        if (pythonCheckBox.isSelected()) skills.append("Python ");
        if (cppCheckBox.isSelected()) skills.append("C++ ");

        // Validate Skills
        if (skills.toString().isEmpty()) {
            JOptionPane.showMessageDialog(frame, "Please select at least one skill.", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Show the details in a message dialog
        JOptionPane.showMessageDialog(frame, "Employee Details:\nName: " + name + "\nAge: " + age + "\nDepartment: " + department + "\nGender: " + gender + "\nSkills: " + skills.toString().trim());
    }

    private void handleResetAction() {
        // Reset all fields
        nameField.setText("");
        ageField.setText("");
        departmentField.setText("");
        maleButton.setSelected(false);
        femaleButton.setSelected(false);
        javaCheckBox.setSelected(false);
        pythonCheckBox.setSelected(false);
        cppCheckBox.setSelected(false);
    }

    public static void main(String[] args) {
        // Run the application
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new EmployeeForm(); // Create and show the EmployeeForm
            }
        });
    }
}

				
			
Key Enhancements:
  1. Validation Logic: Added checks for name, age, department, gender, and skills.

    • Displays error dialogs if any input is missing or incorrect.
    • Age must be a positive integer.
    • Gender must be selected.
    • At least one skill must be selected.
  2. Handling Methods:

    • handleSubmitAction(JFrame frame): Handles the validation and displays the user input or errors.
    • handleResetAction(): Resets all fields to default.

This approach ensures that the user inputs are correctly validated before being processed, providing a more robust and user-friendly application.

Article written by Harshil Bansal, Team edSlash.