0
我正在努力了解如何减少我的代码,以便5个TextField输入全部指向一个事件处理程序类。这一切都有效,只是有很多重复。任何建议表示赞赏。许多操作的一个事件处理程序
继承人的代码:
TextField studentIdTf = new TextField("Student ID");
studentIdTf.setTooltip(new Tooltip("Enter unique Student ID"));
studentIdTf.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
int studentIdTfInt = Integer.parseInt(studentIdTf.getText());
System.out.println(studentIdTfInt);
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
}
});
TextField quizTf = new TextField("Quiz");
quizTf.setTooltip(new Tooltip("Enter Quiz score"));
quizTf.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
int quizTfInt = Integer.parseInt(quizTf.getText());
System.out.println(quizTfInt);
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
}
});
TextField asg1Tf = new TextField("Assignment 1");
asg1Tf.setTooltip(new Tooltip("Enter Assignment 1 score"));
asg1Tf.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
int asg1TfInt = Integer.parseInt(asg1Tf.getText());
System.out.println(asg1TfInt);
if (asg1TfInt < 0) {
throw new InputMismatchException();
}
if (asg1TfInt > 100) {
throw new InputMismatchException();
}
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
catch(InputMismatchException ex2) {
System.out.println("Enter a number within the range 0 - 100");
}
}
});
TextField asg2Tf = new TextField("Assignment 2");
asg2Tf.setTooltip(new Tooltip("Enter Assignment 2 score"));
asg2Tf.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
int asg2TfInt = Integer.parseInt(asg2Tf.getText());
System.out.println(asg2TfInt);
if (asg2TfInt < 0) {
throw new InputMismatchException();
}
if (asg2TfInt > 100) {
throw new InputMismatchException();
}
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
catch(InputMismatchException ex2) {
System.out.println("Enter a number within the range 0 - 100");
}
}
});
TextField examTf = new TextField("Final Exam");
examTf.setTooltip(new Tooltip("Enter Exam score"));
examTf.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
int examTfInt = Integer.parseInt(examTf.getText());
System.out.println(examTfInt);
if (examTfInt < 0) {
throw new InputMismatchException();
}
if (examTfInt > 100) {
throw new InputMismatchException();
}
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
catch(InputMismatchException ex2) {
System.out.println("Enter a number within the range 0 - 100");
}
}
});
太感谢你了,大获成功。 –