我有这个库应用程序,它的 Controller 类中有几个不同的方法。其中之一称为 checkOut,用于 checkout 图书馆项目。
我正试图在按下“结帐”按钮时实现这一点,并希望它可以从我创建的 txt 字段中获取所有必要的信息。
我做了以下操作,当我在运行时按“结帐”时,到处都是红色错误。感谢您的帮助,谢谢!
if (source == checkoutButton)
{
/*JDialog checkout = new JDialog(checkoutContent, "Checkout", true);
JPanel panel = new JPanel();
checkout.setBounds(750, 300, 350, 190);
checkout.setResizable(false);
checkout.add(panel);
checkout.setVisible(true);*/
String borrowerID = userIDTxtField.getText();
String code = itemIDField.getText();
String date = dateField.getText();
String copyString = code.substring(1);
int copy=Integer.valueOf(copyString);
if (ctrl.checkBorrower(borrowerID))
{
boolean valid = false;
SimpleDateFormat sdf1= new SimpleDateFormat("M/dd/yyyy");
sdf1.setLenient(false);
while (!valid)
{
try
{
sdf1.parse(date);
catalogArea.setText(ctrl.checkOut(borrowerID, code, copy, date));
valid = true;
}
catch (Exception e)
{
catalogArea.setText("Date is not valid. Please try again.");
continue;
}
}
}
else
{
catalogArea.setText("Sorry Invalid ID");
}
}
最佳答案
while (!valid)
{
try
{
sdf1.parse(date);
catalogArea.setText(ctrl.checkOut(borrowerID, code, copy, date));
valid = true;
}
catch (Exception e)
{
catalogArea.setText("Date is not valid. Please try again.");
continue;
}
}
如果日期无效,此代码将导致有效的无限循环。 GUI 很可能会被阻止(如果这发生在 EDT 上 - 如果不是在 EDT 上,则 GUI 更新不正确)因此用户将无法更改导致循环的无效日期。
为了解决这个问题,我会查看循环中未显示的第一个更改代码。基本上,dateField
(大概是一个 JTextField
)应该是一个 JSpinner
。
参见 How to Use Spinners在该屏幕截图、工作代码和更多提示的教程中。
如果文本字段是一个微调器,那么整个验证恶作剧就变得多余了。微调器将提供有效(但不一定正确 - 需要用户智能 API)日期。
关于java - 将 GUI 添加到我的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9408639/