gpt4 book ai didi

java - 验证 JavaFX 中的空白字段

转载 作者:行者123 更新时间:2023-11-30 01:33:07 25 4
gpt4 key购买 nike

在数据库中插入数据之前尝试验证空白字段时遇到问题。我目前正在使用 Netbeans JavaFX 应用程序、场景生成器和 MySQL。

对于此方法,它将把面板内的组件传递到 Controller 类中。

private void createProduct(ActionEvent event){
CreateProductController controller = new CreateProductController();
boolean result = controller.create(myPane);
if(result)
{
System.out.println("Success");
}
}

在我的 Controller 类中,我有一个 validateDetails 方法,该方法在插入之前检查空白字段和​​一个创建方法。

public boolean create(CreateProductUI panel){
String name = panel.getNameTextField().getText();
//And the rest of the components which I removed before it's very long

//I used if else statement to check
boolean invalid = true;
if(invalid){
validateDetails(name,desc,priceStr,qtyStr,dateStr,image,category);
return invalid;
}else{
invalid = false;
Product product1 = new Product(name,desc,price,quantity,dateStr,image,category);
product1.create();
return invalid;
}
}

这是我的验证方法:

  public void validateDetails(String name,String desc,String priceStr,String qtyStr,String dateStr,Image image,int category){
if(name.equals("")){
JOptionPane.showMessageDialog(null,"Please enter name");
}else if(desc.equals("")){
JOptionPane.showMessageDialog(null,"Please enter description");
}else if(priceStr.equals("")){
JOptionPane.showMessageDialog(null,"Please enter price");
}else if(qtyStr.equals("")){
JOptionPane.showMessageDialog(null,"Please enter quantity");
}else if(category <= -1){
JOptionPane.showMessageDialog(null,"Please choose category");
}
}

但是,当检测到任何空白字段时,程序不会执行提示错误消息。例如,我将 2 个字段留空。它应该提示两次。相反,它只是添加到我的数据库表中。

提前致谢。

最佳答案

将您的方法更改如下:

public boolean create(CreateProductUI panel){
String name = panel.getNameTextField().getText();
//And the rest of the components which I removed before it's very long

//I used if else statement to check
boolean valid = validateDetails(name,desc,priceStr,qtyStr,dateStr,image,category);

if(valid) {
Product product1 = new Product(name,desc,price,quantity,dateStr,image,category);
product1.create();
}

return valid;
}
}



public boolean validateDetails(String name,String desc,String priceStr,String qtyStr,String dateStr,Image image,int category){

StringBuilder sb = new StringBuilder();
if(name.equals("")){
sb.append(" name ");
}
if(desc.equals("")){
sb.append(" desc ");
}
if(priceStr.equals("")){
sb.append(" Price ");
}
if(qtyStr.equals("")){
sb.append(" Quantity ");
}
if(category <= -1){
sb.append(" Category ");
}
String message = sb.toString();
if(message.length() > 0) {
JOptionPane.showMessageDialog(null,"Please fill up these values: "+message);
return false;
}
return true;
}

关于java - 验证 JavaFX 中的空白字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17213272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com