public class AddingNumbersApp extends Application
1: import javafx.application.Application;
2: import javafx.scene.Scene;
3: import javafx.stage.Stage;
4: import javafx.scene.layout.GridPane;
5: import javafx.scene.layout.BorderPane;
6: import javafx.scene.control.TextField;
7: import javafx.scene.control.Label;
8: import javafx.scene.control.Button;
9: import javafx.geometry.Insets;
10: import javafx.event.ActionEvent;
11: import javafx.event.EventHandler;
12:
13: /**
14: This application embeds a GridPane in the center of a
15: BorderPane. It allows the user to enter numbers into text fields
16: which are added together in the button click event. The sum is
17: displayed in a label in the bottom region of the BorderPane.
18: */
19: public class AddingNumbersApp extends Application
20: {
21: public static void main(String[] args)
22: {
23: launch(args);
24: }
25:
26: @Override
27: public void start(Stage primaryStage) throws Exception
28: {
29: BorderPane root = new BorderPane();
30: // Margin of 10 pixels
31: root.setPadding(new Insets(10,10,10,10));
32:
33: Button btnAdd;
34: TextField txtNum1, txtNum2;
35: Label lblSum;
36:
37: // Add a label message in the top. We create the
38: // label without a named reference since the label
39: // is read-only; we never change it so no reference is needed.
40: root.setTop(new Label("Enter an integer into each textbox " +
41: "and click the button to compute the sum."));
42:
43: // The label that will display the sum goes into the bottom.
44: // Initially it is just a blank string.
45: lblSum = new Label("");
46: root.setBottom(lblSum);
47:
48: // Create a GridPane in the center of the BorderPane
49: GridPane center = new GridPane();
50: center.setVgap(5);
51: center.setHgap(5);
52: txtNum1 = new TextField("0"); // Default text of 0
53: txtNum1.setPrefWidth(150);
54: txtNum2 = new TextField("0");
55: txtNum2.setPrefWidth(150);
56: center.add(new Label("Number 1"), 0, 0);
57: center.add(new Label("Number 2"), 0, 1);
58: center.add(txtNum1, 1, 0);
59: center.add(txtNum2, 1, 1);
60: btnAdd = new Button("Add Numbers");
61: center.add(btnAdd, 1, 2);
62: root.setCenter(center);
63:
64: // Set the event handler when the button is clicked
65: btnAdd.setOnAction(new EventHandler<ActionEvent>()
66: {
67: @Override
68: public void handle(ActionEvent event)
69: {
70: int num1 = Integer.parseInt(txtNum1.getText());
71: int num2 = Integer.parseInt(txtNum2.getText());
72: int sum = num1 + num2;
73: lblSum.setText("The sum is " + sum);
74: }
75: }
76: );
77:
78: Scene scene = new Scene(root, 450, 150);
79: primaryStage.setTitle("Compute the Sum");
80: primaryStage.setScene(scene);
81: primaryStage.show();
82: }
83: }
84: