Ошибка выброса текстового поля

1

У меня есть программа, которая имеет текстовые поля, заполненные пользователем. На основе того, что выбрано в comboBox, требуются разные поля. У меня есть обработчик ошибок, если обязательное поле остается пустым. По какой-то причине я продолжаю получать ошибку для lastName, дня рождения и depatermentName. Может ли кто-нибудь пролить свет на то, почему эти ошибки появляются, даже когда эти поля имеют данные?

Вот мой код...

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.StringJoiner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JComboBox;

@SuppressWarnings("serial")
public class AddEmployeeDisplay extends JFrame
{
    private EmployeeQueries employeeQueries;

    private JPanel displayPanel;
    private JButton addEmpButton;
    private JButton clearButton;
    private JLabel firstNameLabel;
    private JTextField firstNameText;
    private JLabel lastNameLabel;
    private JTextField lastNameText;
    private JLabel SSNLabel;
    private JTextField SSNText;
    private JLabel birthdayLabel;
    private JTextField birthdayText;
    private JLabel employeeTypeLabel;
    private JComboBox<String> employeeTypeCombo;
    private JLabel departmentNameLabel;
    private JTextField departmentNameText;
    private JLabel grossSalesLabel;
    private JTextField grossSalesText;
    private JLabel commissionRateLabel;
    private JTextField commissionRateText;
    private JLabel baseSalaryLabel;
    private JTextField baseSalaryText;
    private JLabel bonusLabel;
    private JTextField bonusText;
    private JLabel hoursLabel;
    private JTextField hoursText;
    private JLabel wageLabel;
    private JTextField wageText;
    private JLabel weeklySalaryLabel;
    private JTextField weeklySalaryText;


    private static final String[] employeeType = {"", "BasePlusCommissionEmployee", "CommissionEmployee", 
                                        "HourlyEmployee", "SalariedEmployee"};

    // Constructor
    public AddEmployeeDisplay()
    {
        super("Add a New Employee");

        // Establish database connection
        employeeQueries = new EmployeeQueries();

        // Create the GUI
        displayPanel = new JPanel();
        employeeTypeLabel = new JLabel();
        employeeTypeCombo = new JComboBox<String>(employeeType);
        employeeTypeCombo.setMaximumRowCount(5);
        firstNameLabel = new JLabel();
        firstNameText = new JTextField();
        lastNameLabel = new JLabel();
        lastNameText = new JTextField();
        SSNLabel = new JLabel();
        SSNText = new JTextField();
        birthdayLabel = new JLabel();
        birthdayText = new JTextField();
        departmentNameLabel = new JLabel();
        departmentNameText = new JTextField();
        grossSalesLabel = new JLabel();
        grossSalesText = new JTextField();
        commissionRateLabel = new JLabel();
        commissionRateText = new JTextField();
        baseSalaryLabel = new JLabel();
        baseSalaryText = new JTextField();
        bonusLabel = new JLabel();
        bonusText = new JTextField();
        hoursLabel = new JLabel();
        hoursText = new JTextField();
        wageLabel = new JLabel();
        wageText = new JTextField();
        weeklySalaryLabel = new JLabel();
        weeklySalaryText = new JTextField();
        clearButton = new JButton();
        addEmpButton = new JButton();

        setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        setSize(500, 600);
        setResizable(false);

        displayPanel.setLayout(new GridLayout(16, 5, 4, 4));    

        employeeTypeLabel.setText("Employee Type: ");
        displayPanel.add(employeeTypeLabel);
        displayPanel.add(employeeTypeCombo);
        employeeTypeCombo.addItemListener(
            new ItemListener()
            {
                public void itemStateChanged(ItemEvent event)
                {
                    if(event.getStateChange() == ItemEvent.SELECTED)
                    {
                        if(employeeTypeCombo.getSelectedItem().toString() == "BasePlusCommissionEmployee")
                        {
                            firstNameText.setEditable(true);
                            lastNameText.setEditable(true);
                            SSNText.setEditable(true);
                            birthdayText.setEditable(true);
                            departmentNameText.setEditable(true);
                            grossSalesText.setEditable(true);
                            commissionRateText.setEditable(true);
                            baseSalaryText.setEditable(true);
                            bonusText.setEditable(true);
                            hoursText.setEditable(false);
                            wageText.setEditable(false);
                            weeklySalaryText.setEditable(false);                            
                        }

                        if(employeeTypeCombo.getSelectedItem().toString() == "CommissionEmployee")
                        {
                            firstNameText.setEditable(true);
                            lastNameText.setEditable(true);
                            SSNText.setEditable(true);
                            birthdayText.setEditable(true);
                            departmentNameText.setEditable(true);
                            grossSalesText.setEditable(true);
                            commissionRateText.setEditable(true);
                            baseSalaryText.setEditable(false);
                            bonusText.setEditable(true);
                            hoursText.setEditable(false);
                            wageText.setEditable(false);
                            weeklySalaryText.setEditable(false);                            
                        }

                        if(employeeTypeCombo.getSelectedItem().toString() == "HourlyEmployee")
                        {
                            firstNameText.setEditable(true);
                            lastNameText.setEditable(true);
                            SSNText.setEditable(true);
                            birthdayText.setEditable(true);
                            departmentNameText.setEditable(true);
                            grossSalesText.setEditable(false);
                            commissionRateText.setEditable(false);
                            baseSalaryText.setEditable(false);
                            bonusText.setEditable(true);
                            hoursText.setEditable(true);
                            wageText.setEditable(true);
                            weeklySalaryText.setEditable(false);                            
                        }

                        if(employeeTypeCombo.getSelectedItem().toString() == "SalariedEmployee")
                        {
                            firstNameText.setEditable(true);
                            lastNameText.setEditable(true);
                            SSNText.setEditable(true);
                            birthdayText.setEditable(true);
                            departmentNameText.setEditable(true);
                            grossSalesText.setEditable(false);
                            commissionRateText.setEditable(false);
                            baseSalaryText.setEditable(false);
                            bonusText.setEditable(true);
                            hoursText.setEditable(false);
                            wageText.setEditable(false);
                            weeklySalaryText.setEditable(true);                         
                        }
                    }                       
                }
            }
        );

        firstNameLabel.setText("First Name: ");
        displayPanel.add(firstNameLabel);
        displayPanel.add(firstNameText);
        firstNameText.setEditable(false);

        lastNameLabel.setText("Last Name: ");
        displayPanel.add(lastNameLabel);
        displayPanel.add(lastNameText);
        lastNameText.setEditable(false);

        SSNLabel.setText("SSN: ");
        displayPanel.add(SSNLabel);
        displayPanel.add(SSNText);
        SSNText.setEditable(false);

        birthdayLabel.setText("Birthday: ");
        displayPanel.add(birthdayLabel);
        displayPanel.add(birthdayText);
        birthdayText.setEditable(false);

        departmentNameLabel.setText("Department Name: ");
        displayPanel.add(departmentNameLabel);
        displayPanel.add(departmentNameText);
        departmentNameText.setEditable(false);

        grossSalesLabel.setText("Gross Sales: ");
        displayPanel.add(grossSalesLabel);
        displayPanel.add(grossSalesText);
        grossSalesText.setEditable(false);

        commissionRateLabel.setText("Commission Rate: ");
        displayPanel.add(commissionRateLabel);
        displayPanel.add(commissionRateText);
        commissionRateText.setEditable(false);

        baseSalaryLabel.setText("Base Salary: ");
        displayPanel.add(baseSalaryLabel);
        displayPanel.add(baseSalaryText);
        baseSalaryText.setEditable(false);

        bonusLabel.setText("Bonus Amount: ");
        displayPanel.add(bonusLabel);
        displayPanel.add(bonusText);
        bonusText.setEditable(false);

        hoursLabel.setText("Hours: ");
        displayPanel.add(hoursLabel);
        displayPanel.add(hoursText);
        hoursText.setEditable(false);

        wageLabel.setText("Wage: ");
        displayPanel.add(wageLabel);
        displayPanel.add(wageText);
        wageText.setEditable(false);

        weeklySalaryLabel.setText("Weekly Salary: ");
        displayPanel.add(weeklySalaryLabel);
        displayPanel.add(weeklySalaryText);
        weeklySalaryText.setEditable(false);
        add(displayPanel);

        clearButton.setText("CLEAR");
        clearButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    clearButtonActionPerformed(evt);
                }                   
            }
        );

        add(clearButton);

        addEmpButton.setText("Add New Employee");
        addEmpButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    addEmpButtonActionPerformed(evt);
                }
            }
        );

        add(addEmpButton);

        addWindowListener(
            new WindowAdapter()
            {
                public void windowClosing(WindowEvent evt)
                {
                    employeeQueries.close();
                    System.exit(0);
                }
            }
        );

        setVisible(true);       
    }

    private void clearButtonActionPerformed(ActionEvent e)
    {
        // Clear the fields so that a new entry may be made.
        SSNText.setText("");
        SSNText.setEditable(false);
        firstNameText.setText("");
        firstNameText.setEditable(false);
        lastNameText.setText("");
        lastNameText.setEditable(false);
        birthdayText.setText("");
        birthdayText.setEditable(false);
        employeeTypeCombo.setSelectedItem("");
        departmentNameText.setText("");
        departmentNameText.setEditable(false);
        grossSalesText.setText("");
        grossSalesText.setEditable(false);
        commissionRateText.setText("");
        commissionRateText.setEditable(false);
        baseSalaryText.setText("");
        baseSalaryText.setEditable(false);
        bonusText.setText("");
        bonusText.setEditable(false);
        hoursText.setText("");
        hoursText.setEditable(false);
        wageText.setText("");
        wageText.setEditable(false);
        weeklySalaryText.setText("");
        weeklySalaryText.setEditable(false);
    }

    // Handles call when addEmpButton is clicked
    private void addEmpButtonActionPerformed(ActionEvent evt)
    {
        int result = 0;
        StringJoiner joiner = new StringJoiner(System.lineSeparator());
        if (employeeTypeCombo.getSelectedItem().toString() == "")
            joiner.add("Employee type missing.");
        if( SSNText.getText() == "" )
            joiner.add("SSN missing.");
        if( firstNameText.getText() == "" )
            joiner.add("First name missing.");
        if( lastNameText.getText() == "" );
            joiner.add("Last name missing.");
        if( birthdayText.getText() == "" );
            joiner.add("Birthday missing.");
        if( departmentNameText.getText() == "" );
            joiner.add("Department name missing.");

        if( joiner.length() != 0 )
        {
            JOptionPane.showMessageDialog(this,
                    joiner.toString(),
                    "Error in input", 
                    JOptionPane.PLAIN_MESSAGE);
            return;
        }

        // Add base plus commission employee data to BasePlusCommissionEmployee table
        if (employeeTypeCombo.getSelectedItem().toString() == "BasePlusCommissionEmployee")
        {
            if( grossSalesText.getText() == "" )
                joiner.add("Gross sales missing.");
            if( commissionRateText.getText() == "" )
                joiner.add("Commission rate missing.");
            if( baseSalaryText.getText() == "" )
                joiner.add("Base salary missing.");
            if( bonusText.getText() == "" )
                joiner.add("Bonus missing.");

            if( joiner.length() != 0 )
            {
                JOptionPane.showMessageDialog(this,
                        joiner.toString(),
                        "Error in input", 
                        JOptionPane.PLAIN_MESSAGE);
                return;
            }

            result = 1;

            employeeQueries.addBPCEmp(SSNText.getText(), grossSalesText.getText(), commissionRateText.getText(),
                                                    baseSalaryText.getText(), bonusText.getText());
        }

        // Add commission employee data to CommissionEmployee table
        if (employeeTypeCombo.getSelectedItem().toString() == "CommissionEmployee")
        {
            if( grossSalesText.getText() == "" )
                joiner.add("Gross sales missing.");
            if( commissionRateText.getText() == "" )
                joiner.add("Commission rate missing.");
            if( bonusText.getText() == "" )
                joiner.add("Bonus missing.");

            if( joiner.length() != 0 )
            {
                JOptionPane.showMessageDialog(this,
                        joiner.toString(),
                        "Error in input", 
                        JOptionPane.PLAIN_MESSAGE);
                return;
            }

            result = 1;

            employeeQueries.addCEmployee(SSNText.getText(), grossSalesText.getText(),
                                                        commissionRateText.getText(), bonusText.getText());
        }

        // Add hourly employee data to HourlyEmployee table
        if (employeeTypeCombo.getSelectedItem().toString() == "HourlyEmployee")
        {
            if( hoursText.getText() == "" )
                joiner.add("Hours missing.");
            if( wageText.getText() == "" )
                joiner.add("Wage missing.");
            if( bonusText.getText() == "" )
                joiner.add("Bonus missing.");

            if( joiner.length() != 0 )
            {
                JOptionPane.showMessageDialog(this,
                        joiner.toString(),
                        "Error in input", 
                        JOptionPane.PLAIN_MESSAGE);
                return;
            }

            result = 1;

            employeeQueries.addHEmployee(SSNText.getText(), hoursText.getText(),
                                                        wageText.getText(), bonusText.getText());
        }

        // Add salaried employee data to SalariedEmployee table
        if (employeeTypeCombo.getSelectedItem().toString() == "SalariedEmployee")
        {
            if( weeklySalaryText.getText() == "" )
                joiner.add("Weekly salary missing.");
            if( bonusText.getText() == "" )
                joiner.add("Bonus missing.");

            if( joiner.length() != 0 )
            {
                JOptionPane.showMessageDialog(this,
                        joiner.toString(),
                        "Error in input", 
                        JOptionPane.PLAIN_MESSAGE);
                return;
            }

            result = 1;

            employeeQueries.addSEmployee(SSNText.getText(), weeklySalaryText.getText(), bonusText.getText());
        }

        // Add Employee data to Employee table
        result += 1;

        employeeQueries.addEmp(SSNText.getText(), firstNameText.getText(), lastNameText.getText(), birthdayText.getText(),
                                            employeeTypeCombo.getSelectedItem().toString(), departmentNameText.getText());

        if(result == 2)
            JOptionPane.showMessageDialog(this, "Employee added!", "Employee added", JOptionPane.PLAIN_MESSAGE);

        else
            JOptionPane.showMessageDialog(this, "Employee not added!", "Error", JOptionPane.PLAIN_MESSAGE);     

        // Clear the fields so that a new entry may be made.
        clearButtonActionPerformed(evt);
    }





    public static void main(String args[])
    {
        AddEmployeeDisplay addEmployeeDisplay = new AddEmployeeDisplay();
    }

}
  • 1
    используйте .equals для сравнения строковых объектов
  • 1
    String всегда должна сравниваться с использованием string1.euals ( string2 ) , а не с == . Более того, вместо присоединения WindowListener просто добавьте эту строку в AddEmployeeDisplay класса setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE ) . И прочитайте про параллелизм в Swing . Способ запуска приложения Swing сомнителен, поскольку Swing должен запускаться в Event Disptacher Thread ( EDT ) .
Теги:
swing

1 ответ

0

Вместо того чтобы сказать if(employeeTypeCombo.getSelectedItem().toString() == "CommissionEmployee"), скажем if(employeeTypeCombo.getSelectedItem().toString().equals("CommissionEmployee")). Поскольку String является классом, он использует методы, чтобы убедиться, что что-то равно. Это не примитивный тип (например, int или boolean), а класс, аналогичный тому, который вы программируете.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню