Java *运算符未定义为JTextField,Double

时间:2017-05-11 22:38:34

标签: java undefined operator-keyword

我收到错误" *运算符未定义为JTextField,Double"在项目的监听者中。它是一个Java GUI项目,我们需要有两个文本字段,一个用于"小时"另一个"率"。我们还需要一个列出员工类型和计算按钮的组合框。我在监听器下的转换案例2(pay = hours * payRate;)中收到错误。如何转换文本以便我可以通过payRate倍增小时数?

public class EmployeeControls extends JPanel
{
private JLabel cost, inputLabel1, inputLabel2, outputLabel, resultLabel;
private JTextField hours, rate;
private JComboBox employeeCombo;
private JButton calculateButton;
private double pay, bonus, payRate;

public EmployeeControls()
{   
    inputLabel1 = new JLabel("Hours:");
    inputLabel2 = new JLabel("Rate:");
    outputLabel = new JLabel("Pay:");
    resultLabel = new JLabel("------");
    hours = new JTextField(2);
    rate = new JTextField(5);
    hours.addActionListener(new CalcListener());
    rate.addActionListener(new CalcListener());

    String[] employeeTypes = {"Select an Employee 
    Type","Salaried","Hourly","Volunteer"};


    employeeCombo = new JComboBox(employeeTypes);

    calculateButton = new JButton("Calculate Pay");

    cost = new JLabel("Pay: " + pay);

    setPreferredSize(new Dimension (400, 100));
    setBackground(Color.cyan);

    add(employeeCombo);
    add(calculateButton);

    calculateButton.addActionListener(new CalcListener());

   }

    private class CalcListener implements ActionListener
   {
    public void actionPerformed (ActionEvent event)
    {

        String text = rate.getText();
        String strRate = Double.toString(payRate);

        String text2 = hours.getText();
        String strHours = Double.toString(hours);


        int employeeType = employeeCombo.getSelectedIndex();

        switch(employeeType)
        {
            case 0:
                JOptionPane.showMessageDialog(null, "Select an Employee 
       Type");
                break;
            case 1:
                pay = (2000.00 + bonus);
                JOptionPane.showMessageDialog(null, "Enter bonus amount");
                break;
            case 2:
                pay = hours * payRate;
                break;
            case 3:
                pay = 0.00;
                break;

        }
        cost.setText("Cost = " + pay);
     }

     }
     }

1 个答案:

答案 0 :(得分:3)

您正在尝试将JTextField整合:它没有意义。

要修复此问题,请使用hours.getText()获取文本字段的值,然后使用int将其解析为Integer.parseInt(hours.getText())。所以它变成了:

pay = Integer.parseInt(hours.getText()) * payRate