JavaFX启动第二个GUI

时间:2018-02-17 04:21:49

标签: java javafx

我想在隐藏我的创建帐户gui之后调用我的LoginUI gui,但是我很难让它工作。 这是我的createAccountUI部分:

package myworkouts.presentation;

import java.util.logging.Level;
import java.util.logging.Logger;
import myworkouts.service.*;
import myworkouts.domain.*;

import javafx.geometry.Insets; 
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.Node;

import javafx.geometry.HPos;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javax.swing.JOptionPane;


public class CreateAccountUI extends Application {

@Override
public void start(Stage primaryStage) throws Exception {

    primaryStage.setTitle("Create Account Form JavaFX Application");

    // Create the registration form grid pane
    GridPane gridPane = createRegistrationFormPane();
    // Add UI controls to the registration form grid pane
    addUIControls(gridPane);
    // Create a scene with registration form grid pane as the root node
    Scene scene = new Scene(gridPane, 800, 500);
    // Set the scene in primary stage   
    primaryStage.setScene(scene);

    scene.getStylesheets().add
        (CreateAccountUI.class.getResource("Login.css").toExternalForm());          
    primaryStage.show();
}


private GridPane createRegistrationFormPane() {
    // Instantiate a new Grid Pane
    GridPane gridPane = new GridPane();

    // Position the pane at the center of the screen, both vertically and horizontally
    gridPane.setAlignment(Pos.CENTER);

    // Set a padding of 20px on each side
    gridPane.setPadding(new Insets(40, 40, 40, 40));

    // Set the horizontal gap between columns
    gridPane.setHgap(10);

    // Set the vertical gap between rows
    gridPane.setVgap(10);

    // Add Column Constraints

    // columnOneConstraints will be applied to all the nodes placed in column one.
    ColumnConstraints columnOneConstraints = new ColumnConstraints(100, 100, Double.MAX_VALUE);
    columnOneConstraints.setHalignment(HPos.RIGHT);

    // columnTwoConstraints will be applied to all the nodes placed in column two.
    ColumnConstraints columnTwoConstrains = new ColumnConstraints(200,200, Double.MAX_VALUE);
    columnTwoConstrains.setHgrow(Priority.ALWAYS);

    gridPane.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);

    return gridPane;
}

private void addUIControls(GridPane gridPane) {
    // Add Header

    Text headerLabel = new Text("Create Account");

    headerLabel.getStyleClass().add("header");

    gridPane.add(headerLabel, 0,0,2,1);
    GridPane.setHalignment(headerLabel, HPos.CENTER);
    GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));


    // Add usernam Label
    Label usernameLabel = new Label("Username*: ");
    gridPane.add(usernameLabel, 0,1);

    // Add unsername Text Field
    TextField usernameField = new TextField();
    usernameField.setPrefHeight(40);
    gridPane.add(usernameField, 1,1);

    // Add Password Label
    Label passwordLabel = new Label("Password* : ");
    gridPane.add(passwordLabel, 0, 2);

    // Add Password Field
    PasswordField passwordField = new PasswordField();
    passwordField.setPrefHeight(40);
    gridPane.add(passwordField, 1, 2);       

    // Add confirm Password Label
    Label conpasswordLabel = new Label("Confirm pwd* : ");
    gridPane.add(conpasswordLabel, 0, 3);

    // Add confirm Password Field
    PasswordField confirmPasswordFld = new PasswordField();
    confirmPasswordFld.setPrefHeight(40);
    gridPane.add(confirmPasswordFld, 1, 3);          

    // Add  first name Label
    Label fnameLabel = new Label("First name : ");
    gridPane.add(fnameLabel, 0,4);

    // Add first name Text Field
    TextField fnameField = new TextField();
    fnameField.setPrefHeight(40);
    gridPane.add(fnameField, 1,4);

    // Add  last name Label
    Label lnameLabel = new Label("Last name : ");
    gridPane.add(lnameLabel, 0,5);

    // Add last name Text Field
    TextField lnameField = new TextField();
    lnameField.setPrefHeight(40);
    gridPane.add(lnameField, 1,5);       

    // Add Email Label
    Label emailLabel = new Label("Email ID : ");
    gridPane.add(emailLabel, 0, 6);

    // Add Email Text Field
    TextField emailField = new TextField();
    emailField.setPrefHeight(40);
    gridPane.add(emailField, 1, 6);

    // Add Required Label
    Label requireLabel = new Label("Required * ");
    gridPane.add(requireLabel, 0,8);

    // Add Submit Button
    Button createButton = new Button("Create");
    createButton.setPrefHeight(40);
    createButton.setDefaultButton(true);
    createButton.setPrefWidth(100);
    gridPane.add(createButton, 1,7);
    GridPane.setHalignment(createButton, HPos.CENTER);
    GridPane.setMargin(createButton, new Insets(20, 0,20,0));        

    // Add Cancel Button
    Button cancelButton = new Button("Cancel");
    cancelButton.setPrefHeight(40);
    cancelButton.setDefaultButton(true);
    cancelButton.setPrefWidth(100);
    gridPane.add(cancelButton, 1,7);
    GridPane.setHalignment(cancelButton, HPos.RIGHT);
    GridPane.setMargin(cancelButton, new Insets(20, 0,20,0));  

    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            System.exit(0);              
        }
    });


    createButton.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            Login login = new Login();
            login.setUsername(usernameField.getText());
            login.setPassword(new String(passwordField.getText()));
            if (!login.validate()) {
                JOptionPane.showMessageDialog(null, "Must supply a username & password", "Error",
                JOptionPane.ERROR_MESSAGE);
            return;
        }

            String confirmPassword = new String(confirmPasswordFld.getText());
            if (!confirmPassword.equals(login.getPassword())) {
                JOptionPane.showMessageDialog(null, "Passwords don't match; try again", "Error",
                JOptionPane.ERROR_MESSAGE);                    
            return;
            } 

            Account account = new Account();
            account.setFirstName(fnameField.getText());
            account.setLastName(lnameField.getText());
            account.setLogin(login);
            boolean isValid = account.validate();
            System.out.println(isValid);
            if (!isValid) {
                JOptionPane.showMessageDialog(null, "Must supply first and last names", "Error",
                JOptionPane.ERROR_MESSAGE);
                return;
            } else {
                // all the fields are non empty; create the account
                AccountSvcCacheImpl impl = AccountSvcCacheImpl.getInstance();
                account = impl.create(account);
                JOptionPane.showMessageDialog(null, "Congratulations, your account has been created", "Account created", 
                JOptionPane.INFORMATION_MESSAGE);
                ((Node)e.getSource()).getScene().getWindow().hide();
                // start LoginUI
                LoginUI loginUI = new LoginUI();


            }      
        }
    });
}

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

这是我的LoginUI:

package myworkouts.presentation;

import javafx.geometry.Insets; 

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Pos;    
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;


public class LoginUI extends Application {

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Forged-Fit Login");


    GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));

    Button btn = new Button("Login");
    Button resetbtn = new Button("Cancel");

    HBox hbBtn = new HBox(10);
    HBox resetBtn = new HBox(10);

    hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
    resetBtn.setAlignment(Pos.BOTTOM_CENTER);

    hbBtn.getChildren().add(btn);
    hbBtn.getChildren().add(resetbtn);

    grid.add(hbBtn, 1, 4);
    grid.add(resetBtn, 0, 3); // might need to adjust

    final Text actiontarget = new Text();
    grid.add(actiontarget, 1, 6);

    Text scenetitle = new Text("Login");

    scenetitle.getStyleClass().add("header");

    grid.add(scenetitle, 0, 0, 2, 1);

    Label userName = new Label("Username : ");
    grid.add(userName, 0, 1);

    TextField userTextField = new TextField();
    grid.add(userTextField, 1, 1);

    Label pw = new Label("Password : ");
    grid.add(pw, 0, 2);

    PasswordField pwBox = new PasswordField();
    grid.add(pwBox, 1, 2);


    Scene scene = new Scene(grid, 400, 200);
    primaryStage.setScene(scene);

    scene.getStylesheets().add
        (LoginUI.class.getResource("Login.css").toExternalForm());      
    primaryStage.show();
}

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

我可以使用节点隐藏创建帐户UI,但似乎无法弄清楚如何显示登录UI。 提前致谢!还在努力学习JavaFX

2 个答案:

答案 0 :(得分:1)

创建LoginUI对象

后尝试添加loginUI.start(new Stage());

答案 1 :(得分:0)

请考虑使用以下示例中的Dialog
使用Dialog可以轻松获取并返回用户的输入。

import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.util.Pair;

//based on:http://code.makery.ch/blog/javafx-dialogs-official/
public class LoginUI extends Dialog {

    LoginUI(){

        setTitle("Login Dialog");
        setHeaderText("Look, a Custom Login Dialog");

        // Set the button types.
        ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
        getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);

        // Create the username and password labels and fields.
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField username = new TextField();
        username.setPromptText("Username");
        PasswordField password = new PasswordField();
        password.setPromptText("Password");

        grid.add(new Label("Username:"), 0, 0);
        grid.add(username, 1, 0);
        grid.add(new Label("Password:"), 0, 1);
        grid.add(password, 1, 1);

        // Enable/Disable login button depending on whether a username was entered.
        Node loginButton = getDialogPane().lookupButton(loginButtonType);
        loginButton.setDisable(true);

        // Do some validation (using the Java 8 lambda syntax).
        username.textProperty().addListener((observable, oldValue, newValue) -> {
            loginButton.setDisable(newValue.trim().isEmpty());
        });

        getDialogPane().setContent(grid);

        // Request focus on the username field by default.
        Platform.runLater(() -> username.requestFocus());

        // Convert the result to a username-password-pair when the login button is clicked.
        setResultConverter(dialogButton -> {
            if (dialogButton == loginButtonType) {
                return new Pair<>(username.getText(), password.getText());
            }
            return null;
        });
    }

    public Pair<String, String> getUserInput(){

        showAndWait();
        return (Pair<String, String>) getResult();
    }
}

通过以下方式测试:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Pair;

public class CreateAccountUI extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        final BorderPane p = new BorderPane();
        p.setCenter(new Label("Random label"));
        p.setPadding(new Insets(100));  // Just so window isn't too small

        final BorderPane cp = new BorderPane();
        final ToggleButton b = new ToggleButton("Show login");
        b.setOnAction(e -> {  showLogin();   });
        cp.setPadding(new Insets(50));
        cp.setCenter(b);

        final Stage control = new Stage();
        control.setScene(new Scene(cp));
        control.show();
    }


    private void showLogin() {

        LoginUI login = new LoginUI();
        Pair<String, String> result = login.getUserInput();
        if(result != null) {
            System.out.println(result.getKey() +"-"+result.getValue());
        }
    }


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

您可以轻松更改您的gui以扩展Dialog