我创建字段和按钮,我的问题是如何使按钮在单击时起作用,以对输入的数字求和并在已创建的新字段中打印总和。
我的代码是:
GridPane gp = new GridPane();
Text txt1 = new Text("Number 1: ");
Text txt2 = new Text("Number 2: ");
Text txt3 = new Text("Result: ");
TextField number1 = new TextField();
TextField number2 = new TextField();
TextField result = new TextField();
Button btn1 = new Button("Sum");
gp.add(txt1, 0, 0);
gp.add(txt2, 0, 1);
gp.add(txt3, 0, 3);
gp.add(number1, 1, 0);
gp.add(number2, 1, 1);
gp.add(result, 1, 3);
gp.add(btn1, 1, 2);
gp.setAlignment(Pos.CENTER);
btn1.setOnAction(e -> {
});
Scene scene = new Scene(gp, 600, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
答案 0 :(得分:0)
首先,您需要将文本字段中的值解析为整数,以便可以添加它们
Integer.parseInt(number1.getText())
然后您只需添加整数
int sum = Integer.parseInt(number1.getText())+Integer.parseInt(number2.getText());
然后您需要获取int的字符串值,以便可以在文本字段中进行设置
String.valueOf(sum)
最终结果看起来像这样
btn1.setOnAction(e -> {
int sum = Integer.parseInt(number1.getText())+Integer.parseInt(number2.getText());
result.setText(String.valueOf(sum));
});