In: Computer Science
Write a JavaFx program for addition of two numbers. (create text as Number1, Number2 and Result and create 3 textfileds. Create sum button. You have to enter number1 and number2 in the textfileds. If you click the button Sum, the result will be showed in the third text field.
package practice;
/* -> Simple calculation: Addition of two numbers using javafx in eclipse
-> Save file name as Calculation.java*/
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label number1=new Label("Number 1 :"); //Label 1
Label number2 = new Label("Number 2 :"); //Label 2
Label result = new Label("Result :"); //Label 3
TextField num1=new TextField(); //text field 1
TextField num2=new TextField(); //text field 2
TextField res=new TextField(); //text field 3
Button sumButton = new Button("Sum");
//Add event listener to sumButton
sumButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Double d1=Double.parseDouble(num1.getText()); //getting the entered in nuber1 textfield and changed to double
Double d2=Double.parseDouble(num2.getText());//getting the entered in nuber2 textfield and changed to double
res.setText(Double.toString(d1+d2)); //set the text to the result textfiled as adddition of two numbers
}
});
/* Adding all Ui elements to root */
GridPane root = new GridPane();
root.addRow(0, number1, num1);
root.addRow(1, number2, num2);
root.addRow(2, result, res);
root.addRow(3, sumButton);
//Scene creation
Scene scene=new Scene(root,500,300);
primaryStage.setScene(scene);
primaryStage.setTitle("Simple Calculation");
primaryStage.show();
}
/* Main Method */
public static void main(String[] args) {
launch(args);
}
}