0
Я пытаюсь понять, как уменьшить мой код, чтобы 5 входов TextField были направлены на один класс обработчика событий. Все работает, так много повторений. Любые советы приветствуются.Один обработчик событий для многих действий
Heres код:
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");
}
}
});
Спасибо так много, большой успех. –