这是退出应用程序的正确方法吗?

时间:2016-03-14 06:30:06

标签: java javafx terminate

我有一个正常运行的JavaFX应用程序。我使用Scene Builder创建了应用程序的GUI,并设法挂钩我的控制器。因此,应用程序从数据库加载数据,然后将数据显示在TableView

因此应用程序设置如下:

控制器:StudenOverview.java

    @Override
public void initialize(URL location, ResourceBundle resources) {

    //SOMETHING IS MISSING HERE, WHAT IS IT?
    regNumber.setCellValueFactory(new PropertyValueFactory<Student, String>("regNumber"));
    name.setCellValueFactory(new PropertyValueFactory<Student, String>("firstName"));
    surname.setCellValueFactory(new PropertyValueFactory<Student, String>("lastName"));
     buildData();
}

public void buildData() {
    BDConnect connection = new BDConnect();
    students = FXCollections.observableArrayList();
    try {
        String loadDataSQL = "SELECT * FROM _students_ ORDER BY _id";
        ResultSet res = connection.connect().createStatement().executeQuery(loadDataSQL);
        while (res.next()) {
            Student st = new Student();
            st.setRegNumber(res.getString(1));
            st.setFirstName(res.getString(2));
            st.setLastName(res.getString(3));
            students.add(st);
        }
        table.setItems(students);
    } catch (SQLException | ClassNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Could not load data, the system will exit!");
        //Of course i will print the error for debugging
        System.exit(-1);
        System.out.println("Could not laod data in the Table!");
    }
}

我的MainApp.java课程:

public class MainApp extends Application {

private Stage primaryStage;

@Override
public void start(Stage primaryStage) {
    this.primaryStage = primaryStage;
    this.primaryStage.setTitle("Student App");
    initRootLayout();

}

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

/**
 * Initializes the root layout.
 */
public void initRootLayout() {
    try {
        // Load root layout from fxml file.
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("view/StudentOverview.fxml"));
        // Show the scene containing the layout.
        Scene scene = new Scene(loader.load());
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

每件事情都运行正常,但我担心的是当buildData方法无法加载数据时,比如由于SQL语法,应用程序将在GUI中显示一个空表。这是bad,因为如果没有表中的数据,用户将无法使用应用程序。所以,在我的情况下,我使用System.exit()退出应用程序。

所以,我的问题:

这是正确的做法吗?你有什么程序员推荐的?如果你在哪里,你会怎么做?

1 个答案:

答案 0 :(得分:2)

System.exit()是强制退出,您可以使用:

Platform.exit();
相关问题