有人可以帮助我在启动程序后立即从数据库加载数据,即在start方法中。我可以在点击的按钮上加载它,但在start方法中,我得到一个NullPointerException。这是代码:
public class Main extends Application {
Controller objekt = new Controller();
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("FXML/sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root));
objekt.učitajRadnike();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
public class Controller {
@FXML
TableView<radnici> radniciTabela;
@FXML
TableColumn<radnici, String> ime = new TableColumn<>();
@FXML
TableColumn<radnici, String> adresa = new TableColumn<>();
@FXML
TableColumn<radnici, String> grad = new TableColumn<>();
@FXML
TableColumn<radnici, String> telefon = new TableColumn<>();
@FXML
TableColumn<radnici, String> email = new TableColumn<>();
@FXML
Button učitajBtn;
ObservableList<radnici> lista;
public ObservableList<radnici> getData() {
lista = FXCollections.observableArrayList();
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/radnici", "root", "Kvark");
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery("SELECT *FROM kontaktinfo");
while (rs.next()) {
lista.add(
new radnici(rs.getString("ime"),
rs.getString("adresa"),
rs.getString("grad"),
rs.getString("telefon"),
rs.getString("email")));
}
System.out.println("umetanje u listu završeno");
} catch (Exception e) {
System.out.println("Greška je " + e);
}
return lista;
}
@FXML
public void učitajRadnike() {
ime.setCellValueFactory(new PropertyValueFactory<radnici, String>("ime"));
adresa.setCellValueFactory(new PropertyValueFactory<radnici, String>("adresa"));
grad.setCellValueFactory(new PropertyValueFactory<radnici, String>("grad"));
telefon.setCellValueFactory(new PropertyValueFactory<radnici, String>("telefon"));
email.setCellValueFactory(new PropertyValueFactory<radnici, String>("email"));
radniciTabela.setItems(getData());
}
}
这可能是微不足道的,但我真的不明白。该方法不应为null,它适用于单击按钮。顺便说一句,我正在使用SceneBuilder添加动作,并创建UI。