是否有替代方法来检查 javafx 应用程序中的许多空白字段?

我是java(以及一般编程)的新手,并且正在通过将基本电子表格转换为javafx应用程序来学习。为此,我使用:Java & JavaFX 12 FXML & GUI 的 scenebuilder

大约有 10 个输入字段,并且它们不能为空(应用程序崩溃,因为 getText 似乎在空白字段上失败)。

我编写了堆叠的 if 语句来检查空白字段,然后打印错误消息(如果有),并返回以停止进程而不会使应用程序崩溃。

switch 语句似乎并不比 if 语句好多少。

有没有一种方法可以用更少的代码行来完成它?


梵蒂冈之花
浏览 71回答 1
1回答

不负相思意

您需要以某种方式将一个字段与一个字符串关联起来。这需要您为每个TextFields 添加一些代码,无论是userData在 fxml 中设置 ,还是将TextField和的组合存储String在控制器initialize方法中合适的数据结构中。这样的数据结构可以是LinkedHashMap:private final Map<TextField, String> fieldStrings = new LinkedHashMap<>();@FXMLprivate void initialize() {&nbsp; &nbsp; fieldStrings.put(desShear, "Design shear");&nbsp; &nbsp; fieldStrings.put(boltSize, "Bolt size");&nbsp; &nbsp; fieldStrings.put(tensStrengthBolt, "Bolt strength");&nbsp; &nbsp; fieldStrings.put(noBolts, "Number of bolts");&nbsp; &nbsp; fieldStrings.put(shearPlanes, "Number of shear planes");&nbsp; &nbsp; fieldStrings.put(edgeDist, "Edge distance");&nbsp; &nbsp; fieldStrings.put(plyThick, "Ply thickness");&nbsp; &nbsp; fieldStrings.put(tensStrengthPly, "Ply strength");&nbsp; &nbsp; fieldStrings.put(phiBolt, "Bolt phi factor");&nbsp; &nbsp; fieldStrings.put(phiPly, "Ply phi factor");}private double getFieldValue(TextField field) {&nbsp; &nbsp; return Double.parseDouble(field.getText());}public void run(ActionEvent clickRun) {&nbsp; &nbsp; String errorField = fieldStrings.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(entry -> entry.getKey().getText().isBlank())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(Map.Entry::getValue)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.findFirst().orElse(null);&nbsp; &nbsp; if (errorField != null) {&nbsp; &nbsp; &nbsp; &nbsp; outputMsg.setText(errorField + " field is blank");&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; //Get field values&nbsp; &nbsp; double desSHEAR = getFieldValue(desShear);&nbsp; &nbsp; double boltSIZE = getFieldValue(boltSize);&nbsp; &nbsp; double tensStengthBOLT = getFieldValue(tensStrengthBolt);&nbsp; &nbsp; double noBOLTS = getFieldValue(noBolts);&nbsp; &nbsp; double shearPLANES = getFieldValue(shearPlanes);&nbsp; &nbsp; double edgeDIST = getFieldValue(edgeDist);&nbsp; &nbsp; double plyTHICK = getFieldValue(plyThick);&nbsp; &nbsp; double tensStrengthPLY = getFieldValue(tensStrengthPly);&nbsp; &nbsp; double phiBOLT = getFieldValue(phiBolt);&nbsp; &nbsp; double phiPLY = getFieldValue(phiPly);&nbsp; &nbsp; //Bolt shear calculation}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java