我正在通过将基本电子表格转换为javafx应用程序来学习。为此,我正在使用:Java和JavaFX 12 FXML和Scenebuilder for GUI
大约有10个输入字段,它们不能为空(应用程序崩溃,因为getText似乎在空白字段上失败)。
我编写了堆叠的if语句来检查空白字段,然后打印错误消息(如果有的话),并返回以停止该过程而不会崩溃该应用程序。
switch语句似乎没有if语句更好。
有没有办法用更少的代码行做到这一点?
package SteelDesign_BoltedConnection;
import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.scene.control.DatePicker; import javafx.scene.control.TextArea; import javafx.event.ActionEvent;
public class mainController {
//Header details
@FXML private TextField refNo;
@FXML private TextField jobDesc;
@FXML private TextField author;
@FXML private DatePicker date;
//Design data
@FXML private TextField desShear;
@FXML private TextField boltSize;
@FXML private TextField boltGrade;
@FXML private TextField tensStrengthBolt;
@FXML private TextField noBolts;
@FXML private TextField shearPlanes;
@FXML private TextField edgeDist;
@FXML private TextField plyThick;
@FXML private TextField tensStrengthPly;
//Constants
@FXML private TextField phiBolt;
@FXML private TextField phiPly;
//Results - Bolt Shear
@FXML private TextField boltDesShear;
@FXML private TextField boltCap;
@FXML private TextField loadFactorBolt;
您需要一种或另一种方式将一个字段与一个字符串关联。这需要你添加一些代码对于每个的TextFieldS,不管是设置userData在FXML或存储的compination TextField和String在控制器的一个合适的数据结构initialize的方法。
这样的数据结构可能是LinkedHashMap:
private final Map<TextField, String> fieldStrings = new LinkedHashMap<>();
@FXML private void initialize() { fieldStrings.put(desShear, "Design shear"); fieldStrings.put(boltSize, "Bolt size"); fieldStrings.put(tensStrengthBolt, "Bolt strength"); fieldStrings.put(noBolts, "Number of bolts"); fieldStrings.put(shearPlanes, "Number of shear planes"); fieldStrings.put(edgeDist, "Edge distance"); fieldStrings.put(plyThick, "Ply thickness"); fieldStrings.put(tensStrengthPly, "Ply strength"); fieldStrings.put(phiBolt, "Bolt phi factor"); fieldStrings.put(phiPly, "Ply phi factor"); }
private double getFieldValue(TextField field) { return Double.parseDouble(field.getText()); }
public void run(ActionEvent clickRun) {
String errorField = fieldStrings.entrySet().stream()
.filter(entry -> entry.getKey().getText().isBlank())
.map(Map.Entry::getValue)
.findFirst().orElse(null);
if (errorField != null) {
outputMsg.setText(errorField + " field is blank");
return;
}
//Get field values
double desSHEAR = getFieldValue(desShear);
double boltSIZE = getFieldValue(boltSize);
double tensStengthBOLT = getFieldValue(tensStrengthBolt);
double noBOLTS = getFieldValue(noBolts);
double shearPLANES = getFieldValue(shearPlanes);
double edgeDIST = getFieldValue(edgeDist);
double plyTHICK = getFieldValue(plyThick);
double tensStrengthPLY = getFieldValue(tensStrengthPly);
double phiBOLT = getFieldValue(phiBolt);
double phiPLY = getFieldValue(phiPly);
//Bolt shear calculation
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。