Java NoSuchMethodException - 类中确实存在方法

时间:2015-10-03 10:41:44

标签: java javafx nosuchmethod

我正在构建一个JavaFx应用程序,我想创建一个接收GridPane和Node []的方法,其中包含添加到窗格的项目数量。但是,当我调用该方法时,我得到一个NoSuchMethodException。

作为测试,我尝试创建一个private String helloWorld()的简单方法return "Hello World";。此方法确实有效,但当我尝试运行gridLogin = buildForm(gridLogin, items);时,出现Exception in thread "main" java.lang.NoSuchMethodException错误。

Application.java

public class DesktopApplication extends Application {

    @Override
    public void start(Stage primaryStage) {
        BuildGraphicalUserInterface ui = new BuildGraphicalUserInterface();
        ui.initStage(primaryStage);
    }
}

BuildGraphicalUserInterface.java

package com.fenrir.desktop.UserInterface;

import ...;

public class BuildGraphicalUserInterface {

    private final String APP_TITLE = "Fenrir Desktop App";
    private final String LOGIN_HEADER = "FENRIR secure";

    Stage stage;
    Scene sceneLogin, sceneMain, sceneRegister;
    GridPane gridLogin, gridMain, gridRegister;

    long startTime, endTime;

    boolean authorized;
    Optional<String> result;

    public void initStage(Stage primaryStage) {
        stage = primaryStage;
//        Set global ui options
        stage.setTitle(APP_TITLE);
        stage.setResizable(false);

//        Setup every screen in application
        initScenes(stage);
    }

    private void initScenes(Stage stage) {
        startTime = System.nanoTime();
        sceneLogin = buildLoginScreen();
        endTime = System.nanoTime();
        System.out.println("login:\t" + (endTime - startTime));

        startTime = System.nanoTime();
        sceneMain = buildMainScreen();
        endTime = System.nanoTime();
        System.out.println("main:\t" + (endTime - startTime));

        startTime = System.nanoTime();
        sceneRegister = buildRegisterScreen();
        endTime = System.nanoTime();
        System.out.println("register:\t" + (endTime - startTime));
        stage.setScene(sceneLogin);
        stage.show();
    }

//    BUILD OF SCREENS
    private Scene buildLoginScreen() {
        gridLogin = new GridPane();
        gridLogin.setAlignment(Pos.CENTER);
        gridLogin.setVgap(10);
        gridLogin.setHgap(10);

        Text loginTitle = new Text(LOGIN_HEADER);
        loginTitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        Label usernameLabel = new Label("Username:");
        final TextField usernameTextField = new TextField();
        Label companyLabel = new Label("Company:");
        final TextField companyTextField = new TextField();
        Button loginButton = new Button("Login");
        Hyperlink registerLink = new Hyperlink();
        registerLink.setText("Register");

        registerLink.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                stage.setScene(sceneRegister);
            }
        });

        loginButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                UserAuthentication auth = new UserAuthentication(usernameTextField.getText(), companyTextField.getText());
                try {
//                    check if user exists
                    auth.authenticate();

//                    show token pop up
                    promptTokenAlert();
                    if (result.isPresent()) {
                        if (auth.verifyToken(result.get())) {
                            authorized = true;
                            stage.setScene(sceneMain);
                        }
                        else
                            wrongTokenAlert();
                    }
                } catch (IOException e1) {
                    userNotFoundAlert();
                    usernameTextField.setText("");
                    companyTextField.setText("");
                }
            }});

        Node[] items = new Node[6];
        items[0] = loginTitle;
        items[1] = usernameLabel;
        items[2] = usernameTextField;
        items[3] = companyLabel;
        items[4] = companyTextField;
        items[5] = loginButton;
        items[6] = registerLink;
        gridLogin = buildForm(gridLogin, items);

        sceneLogin = new Scene(gridLogin, 300, 200);

        return sceneLogin;
    }

    private Scene buildMainScreen() {
        gridMain = new GridPane();

        final Label authorizedLabel = new Label("Authorized!");
        Button logoutButton = new Button("Logout");

        logoutButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                authorized = false;
                stage.setScene(sceneLogin);
            }});

        gridMain.add(authorizedLabel, 0, 0);
        gridMain.add(logoutButton, 0, 1);
        sceneMain = new Scene(gridMain, 800, 600);

        return sceneMain;
    }

    private Scene buildRegisterScreen() {
        gridRegister = new GridPane();
        gridRegister.setAlignment(Pos.CENTER);
        gridRegister.setVgap(10);
        gridRegister.setHgap(10);
        sceneRegister = new Scene(gridRegister, 300, 200);

        Label userName = new Label("Username:");
        final TextField userTextField = new TextField();
        Label company = new Label("Company:");
        final TextField companyTextField = new TextField();
        Label phoneNumber = new Label("Phone nr.:");
        final TextField phoneNumberTextField = new TextField();
        Button registerButton = new Button("Register");
        Hyperlink returnLabel = new Hyperlink();
        returnLabel.setText("Go back");

        returnLabel.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                stage.setScene(sceneLogin);
            }
        });
        registerButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                /**
                 * register response
                 * 1 - user already exists
                 * 2 - incorrect username
                 * 3 - incorrect phonenumber
                 * 4 - unknown error
                 * 0 - success
                 */
                int registerResponse;
                UserRegistration userReg = new UserRegistration(userTextField.getText(), companyTextField.getText(), phoneNumberTextField.getText());
                try {
                    registerResponse = userReg.Register();
                } catch (IOException e) {
                    registerResponse = 4;
                    e.printStackTrace();
                }
                if (registerResponse == 0) {
                    userRegisteredConfirmation();
                    stage.setScene(sceneLogin);
                } else {
                    userRegistrationErrorAlert(registerResponse);
                }
            }
        });

        gridRegister.add(userName, 0, 1);
        gridRegister.add(userTextField, 1, 1);
        gridRegister.add(company, 0, 2);
        gridRegister.add(companyTextField, 1, 2);
        gridRegister.add(phoneNumber, 0, 3);
        gridRegister.add(phoneNumberTextField, 1, 3);
        gridRegister.add(registerButton, 1, 4);
        gridRegister.add(returnLabel, 0, 4);

        return sceneRegister;
    }

    /**
     * Builds a form with items received (items should be sorted)
     * @param grid
     * @param items
     * @return
     */
    private GridPane buildForm(GridPane grid, Node[] items) {
        int row = 0;
        for (int i = 0; i < items.length; i++) {
            grid.add(items[i], i, row);
            if (i % 2 == 0)
                row++;
        }

        return grid;
    }

//    ALERTS
    /**
     * Alert is shown when service returns no user
     * @return
     */
    private Alert userNotFoundAlert() {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("FENRIR security");
        alert.setHeaderText("Error");
        alert.setContentText("User not recognized");
        alert.showAndWait();
        return alert;
    }

    /**
     * Alert is shown when user should enter token
     * @return
     */
    private TextInputDialog promptTokenAlert() {
        TextInputDialog alert = new TextInputDialog("");
        alert.setTitle("FENRIR security");
        alert.setHeaderText("Token requested");
        result = alert.showAndWait();
        return alert;
    }

    /**
     * Alert is shown when entered token is wrong
     * @return
     */
    private Alert wrongTokenAlert() {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("FENRIR security");
        alert.setHeaderText("Token incorrect");
        alert.showAndWait();
        return alert;
    }

    /**
     * Confirmation is shown when registration is completed
     * @return
     */
    private Alert userRegisteredConfirmation() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("FENRIR security");
        alert.setHeaderText("Success");
        alert.setContentText("Registration completed");
        alert.showAndWait();
        return alert;
    }

    /**
     * Alert is shown when an error occurs during registration
     * @param errorCode
     * @return
     */
    private Alert userRegistrationErrorAlert(int errorCode) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("FENRIR security");
        alert.setHeaderText("Error");
        String errorMessage;
        switch (errorCode) {
            case 1: errorMessage = "User already exists.";
                break;
            case 2: errorMessage = "Incorrect username. Username should be at least 2 characters.";
                break;
            case 3: errorMessage = "Incorrect phone number. Should be 8 characters and only numbers.";
                break;
            default: errorMessage = "Unknown error. Contact administrator.";
        }
        alert.setContentText(errorMessage);
        alert.showAndWait();
        return alert;
    }
}

堆栈跟踪

Exception in Application start method
Exception in thread "main" java.lang.NoSuchMethodException: com.fenrir.desktop.DesktopApplication.main([Ljava.lang.String;)
    at java.lang.Class.getMethod(Class.java:1786)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)

Process finished with exit code 1

1 个答案:

答案 0 :(得分:1)

这将解决你的问题,安装e(fx)clipse这个eclise插件,但我不知道intellij,或为你的应用程序添加facet作为javafx应用程序,如果你添加facet你不需要main方法,或使用像这样

public class DesktopApplication extends Application {

    @Override
    public void start(Stage primaryStage) {
        BuildGraphicalUserInterface ui = new BuildGraphicalUserInterface();
        ui.initStage(primaryStage);
    }

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