我正在写一个餐厅应用程序。
在这一部分中,为了添加厨师,用户需要在nameTextField中输入厨师的名称,并在SalaryTextField中输入Cook的工资,在名称部分我要防止用户输入数字,在工资部分要防止用户输入从输入单词开始。对于薪水部分,我尝试使用异常处理,但无法真正成功。
class AddButtonInCookClick implements ActionListener{
public void actionPerformed(ActionEvent e) {
String name = (String)nameTextFieldCook.getText();
double salary = new Double(0.0);
try {
salary = Double.parseDouble(salaryTextField.getText());
}catch(NumberFormatException ex) {
System.out.println(ex);
}
restaurant.getEmployees().add(new Cook(id, name, salary));
id++;
JOptionPane cookOptionPane = new JOptionPane();
JOptionPane.showMessageDialog(cookOptionPane, "Cook added succesfully.");
}
}
addButtonInCook.addActionListener(new AddButtonInCookClick());
即使程序不会崩溃。我仍然无法让用户输入薪水部分的数字。谢谢你的帮忙。
最佳答案
您可以使用JFormattedTextField
代替普通的JTextField
将输入仅限制为数字。
样例代码:
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import java.text.NumberFormat;
import javax.swing.text.NumberFormatter;
public class Test extends JFrame
{
JFormattedTextField salaryFormattedTextField;
NumberFormat numberFormat;
NumberFormatter numberFormatter;
public Test()
{
numberFormat = NumberFormat.getInstance();
// delete line if you want to see commas or periods grouping numbers based on your locale
numberFormat.setGroupingUsed(false);
numberFormatter = new NumberFormatter(format);
numberFormatter.setValueClass(Integer.class);
// delete line if you want to allow user to enter characters outside the value class.
// Deleting the line would allow the user to type alpha characters, for example.
// This pretty much defeats the purpose of formatting
numberFormatter.setAllowsInvalid(false);
salaryFormattedTextField = new JFormattedTextField(formatter);
this.add(salaryFormattedTextField);
}
public static void main(String[] args)
{
Test test = new Test();
s.pack();
s.setVisible(true);
}
}
使用您已有的代码结构的替代方法是,当输入无法正确解析时抛出JOptionPane。
try
{
salary = Double.parseDouble(salaryTextField.getText());
restaurant.getEmployees().add(new Cook(id, name, salary));
id++;
JOptionPane cookOptionPane = new JOptionPane();
JOptionPane.showMessageDialog(cookOptionPane, "Cook added succesfully.");
}
catch(NumberFormatException ex)
{
JOptionPane cookFailPane = new JOptionPane();
JOptionPane.showMessageDialog(cookFailPane , "Could not add cook. Please enter salary using only numeric input.");
ex.printStackTrace();
}