[英]JavaFX button listener not working
我正在创建一个简单的计算器,该计算器将在文本字段中输入的两个值相加,然后在按下按钮时在第三文本字段中显示总和。 但是,当我按下按钮时,什么也没有发生,而且我无法弄清楚出了什么问题。 我没有收到任何错误消息,程序会编译按钮,但似乎什么都没做。
import javafx.application.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.event.*;
public class Calculator extends Application{
private TextField sumField;
private TextField firstVField;
private TextField secondVField;
public void start(Stage myStage){
myStage.setTitle("Simple Calculator");
GridPane rootNode = new GridPane();
rootNode.setPadding(new Insets(30));
rootNode.setHgap(5);
rootNode.setVgap(5);
Scene myScene = new Scene(rootNode, 350,250);
Label firstVLabel = new Label("First Value:");
Label secondVLabel = new Label("Second Value:");
Label sumLabel = new Label("Sum:");
TextField firstVField = new TextField();
TextField secondVField = new TextField();
TextField sumField = new TextField();
sumField.setEditable(false);
Button calculate = new Button("Calculate");
rootNode.add(firstVLabel, 0, 0);
rootNode.add(firstVField, 1, 0);
rootNode.add(secondVLabel, 0, 1);
rootNode.add(secondVField, 1, 1);
rootNode.add(sumLabel, 0, 2);
rootNode.add(sumField, 1, 2);
rootNode.add(calculate, 1, 3);
myStage.setScene(myScene);
myStage.setResizable(false);
myStage.show();
}
class ButtonHandler implements EventHandler<ActionEvent>{
public void handle(ActionEvent e) {
int sum = (int)firstVField.getText() + (int)secondVField.getText();
sumField.setText(Integer.toString(sum));
}
}
public static void main( String [] args){
launch(args);
}
}
您忘记了将ButtonHandler
连接到calculate
按钮
calculate.setOnAction(new ButtonHandler());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.