I have a JavaFX application that is working properly. I have created the application's GUI using Scene Builder and I managed to hook my controller. So, the application loads data from a database which is then displayed in an a TableView
.
So the application is setup like this:
Controller: 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!");
}
}
My MainApp.java
class:
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();
}
}
}
Every thing is working fine but my concern is when the buildData
method fails to load data, say due to an SQL syntax, the application will display an empty table in the GUI. This is bad
because the user will not be able to work with the application without data in the table. So, in my case I have used System.exit()
to exit from the application.
So, my questions:
Is this the proper way of doing it? What do you programmers recommend? How would you do it if where you?
System.exit() is a force exit, you may use this:
Platform.exit();