【发布时间】:2016-03-14 14:52:23
【问题描述】:
我有一个运行正常的 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() 退出应用程序。
那么,我的问题:
这是正确的做法吗?程序员有什么推荐的?如果你在哪里,你会怎么做?
【问题讨论】:
-
您至少应该在某个时候使用
Application.stop方法来确保您的资源正常关闭。请参阅docs.oracle.com/javafx/2/api/javafx/application/… 上有关 JavaFX 应用程序生命周期的部分 -
@AustinD 我应该在哪里调用该方法?在我的控制器类中?
-
当您关闭应用程序(例如,通过单击窗口上的 X 按钮)时,会自动调用
stop方法。 -
@AustinD 是的,这很好,但我问的是我的情况,因为如果应用程序无法加载数据,它就不能继续执行
-
exit方法的int参数如果不为0则表示错误,我认为-1不是正确的值,见标准pubs.opengroup.org/onlinepubs/9699919799//utilities/…