0% found this document useful (0 votes)
0 views

java fx app

Uploaded by

Joclyn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

java fx app

Uploaded by

Joclyn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

package javafxapp;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

// Main class representing the JavaFX application


public class JavaFXapp extends Application {

// Entry point of the JavaFX application


@Override
public void start(Stage primaryStage) {
// Label to display the result
Label result = new Label();

// TextFields for user input


TextField m1 = new TextField();
m1.setPromptText("Enter number 1");

TextField m2 = new TextField();


m2.setPromptText("Enter number 2");

// Button to trigger the calculation


Button calculate = new Button();
calculate.setText("Calculate");
calculate.setOnAction(new EventHandler<ActionEvent>() {

// Event handler for the button click


@Override
public void handle(ActionEvent event) {
try {
// Parse the input and calculate the sum
int num1 = Integer.parseInt(m1.getText());
int num2 = Integer.parseInt(m2.getText());
int sum = num1 + num2;
result.setText("The sum is: " + sum);
} catch (NumberFormatException e) {
// Handle invalid input (non-integer input)
result.setText("Invalid input! Please enter two valid
integers.");
}
}
});

// Layout for organizing the UI components


VBox root = new VBox();
root.setPadding(new Insets(10));
root.setSpacing(5);
root.getChildren().addAll(m1, m2, calculate, result);

// Scene that holds the root layout


Scene scene = new Scene(root, 300, 250);

// Set up the primary stage (main window) of the application


primaryStage.setTitle("Add two numbers");
primaryStage.setScene(scene);
primaryStage.show();
}

// Main method to launch the JavaFX application


public static void main(String[] args) {
launch(args);
}

You might also like