Wednesday, July 23, 2014

Check and parse number from String


package javafx_parsenum;

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.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ParseNum extends Application {
    
    @Override
    public void start(Stage primaryStage) {

        TextField textField = new TextField ();
        Label answer1 = new Label();
        Label answer2 = new Label();
        Label answer3 = new Label();
        
        Button btnCheck = new Button();
        btnCheck.setText("- Check -");
        btnCheck.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                
                String q = textField.getText();

                try{
                    double parseDouble = Double.parseDouble(q);
                    answer1.setText("Double: " + String.valueOf(parseDouble));
                }catch(NumberFormatException ex){
                    answer1.setText("Not a valid Double");
                }
                
                try{
                    float parseFloat = Float.parseFloat(q);
                    answer2.setText("Float: " + String.valueOf(parseFloat));
                }catch(NumberFormatException ex){
                    answer2.setText("Not a valid Float");
                }
                
                try{
                    int parseInt = Integer.parseInt(q);
                    answer3.setText("Integer: " + String.valueOf(parseInt));
                }catch(NumberFormatException ex){
                    answer3.setText("Not a valid Integer");
                }

            }
        });
        
        VBox vBox = new VBox();
        vBox.setSpacing(5);
        vBox.getChildren().addAll(textField, btnCheck,
            answer1, answer2, answer3);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 560, 315);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

No comments:

Post a Comment