首页 > 解决方案 > JAVA FX 类 GUI

问题描述

下面的程序利用 java fx 类创建一个图形用户界面来验证一个人是否有资格喝酒。问题是输出显示在控制台上而不是图形用户界面上 I. 我该如何解决这个问题?

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ValidateAge extends Application {
   //Class Variables 
    Stage window;
    Scene scene;
    Button button;

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

    @Override //Method that creates Graphical User Interface 
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("Validate Age For Drinking");// displays "Validate age" on top of window

         TextField ageInput = new TextField();// Object for display text field 
         Label label1 = new Label();
        button = new Button("Verify Age"); //Displays Verify Age Buttom 
        button.setOnAction( e -> isInt(ageInput, ageInput.getText() , label1));

        //Parameters for Layouts 
        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20, 20)); //sets the size of the layout
        layout.getChildren().addAll(ageInput, label1, button);

        scene = new Scene(layout, 400, 550);//sets dimensions for scene 
        window.setScene(scene); 
        window.show();
    }

    //Validates user age
    private  int isInt(TextField input, String message, Label label){
        // validates to see if user is above 18 to drink
        try{ 
            int age = Integer.parseInt(input.getText());
            if(age< 18) {
            label.setText("You are not allowed to drink");

            }else {
            System.out.println("You are   allowed to drink");
            }
         }catch(NumberFormatException e){ // displays when user fails to type in a  number 
            System.out.println("Error: " + message + " Tye in a number ");
         }
        return 0;
    }


}

标签: user-interfacejavafx

解决方案


代替

System.out.println("You are   allowed to drink"); 

label.setText("You are allowed to drink");

你很高兴。


推荐阅读