【发布时间】:2017-05-11 22:38:34
【问题描述】:
我在项目的侦听器中收到错误“* Operator Undefined for JTextField, Double”。这是一个 Java GUI 项目,我们需要有两个文本字段,一个用于“小时”,另一个用于“费率”。我们还需要有一个列出员工类型的组合框和一个计算按钮。我在监听器下的 switch case 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);
}
}
}
【问题讨论】:
-
pay = hours * payRate-hours是一个JTextField,你怎么能把它乘以一个双倍? -
String strHours = Double.toString(hours);也会出于类似的原因给您带来问题 -
@MadProgrammer 我们需要使用文本字段,支付率需要有小数,所以我不相信我可以使用整数。你会用什么类型的?
-
Double.toString(hours)需要double值。我认为你所有的转换都是向后的,你想把String解析为double,这意味着你需要先从文本字段中获取String文本
标签: java undefined operator-keyword