2014-03-25 3 views
1

Я хотел бы добавить значения в таблицу Javafx.Невозможно заполнить таблицу Javafx Вид из базы данных

Значения хранятся в удаленной базе данных.

Способ получения значений из разряда (setAll(service.listReservierung()) работает по назначению. Когда я пытаюсь запустить следующий код, чтобы поместить значения в таблицу Javafx, я получаю полный список ошибок, первый из которых является исключением Null. Вот код:

public void listReserv() { 
    try { 

    AlleReservTable.getItems().setAll(service.listReservierung()); 

    tableColumnReservNr.setCellValueFactory(
      new PropertyValueFactory<Reservierung, Integer>("reservNr")); 

    tableColumnReservName.setCellValueFactory(
      new PropertyValueFactory<Reservierung, String>("kundeName")); 

    tableColumnReservVon.setCellValueFactory(
      new PropertyValueFactory<Reservierung, Timestamp>("von")); 

    tableColumnReservBis.setCellValueFactory(
      new PropertyValueFactory<Reservierung, Timestamp>("bis")); 

} catch(Exception e) { 
    e.printStackTrace(); 
} 
} 
+0

В какой строке возникает NullPointerException? Вы начали столбцы таблицы? –

+0

На первом, если я прокомментирую это, а затем на втором и т. Д. Как мне начать столбцы таблицы? – Syn

+0

Если класс не является классом контроллера JavaFX, т. Е. Если столбцы таблицы не определены в FXML, вы должны их инициировать. Например: TableColumn tableColumnReservNr = new TableColumn <> («Reserv Nr»); и так далее. –

ответ

1

Хей, я сделал рабочий пример для вас, я использовал новый API Дата Время от Java8. Служба ReservationService не запрашивает базу данных, чтобы проверить этот случай, вам придется опубликовать свой класс службы. Возможно, этот пример поможет вам.

FXML Файл

<?xml version="1.0" encoding="UTF-8"?> 

<?import java.lang.*?> 
<?import javafx.scene.control.*?> 
<?import javafx.scene.layout.*?> 

<AnchorPane fx:controller="de.professional_webworkx.reservationmanager.controller.MainController" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="768.0" prefWidth="1024.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"> 
<children><TableView fx:id="reservationTable" prefHeight="768.0" prefWidth="1024.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" xmlns:fx="http://javafx.com/fxml"> 
    <columns> 
    <TableColumn fx:id="resNumber" minWidth="250.0" prefWidth="250.0" text="ReservationID" /> 
    <TableColumn fx:id="customerName" minWidth="450.0" prefWidth="500.0" text="CustomerName" /> 
    <TableColumn fx:id="checkIn" minWidth="100.0" prefWidth="100.0" text="CheckIn" /> 
    <TableColumn fx:id="checkOut" minWidth="100.0" prefWidth="100.0" text="CheckOut" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" /> 
    </columns> 
</TableView> 
</children></AnchorPane> 

MainController

package de.professional_webworkx.reservationmanager.controller; 

import de.professional_webworkx.reservationmanager.business.ReservationService; 
import de.professional_webworkx.reservationmanager.model.Reservation; 
import java.net.URL; 
import java.time.LocalDateTime; 
import java.util.List; 
import java.util.ResourceBundle; 
import javafx.beans.property.ObjectProperty; 
import javafx.beans.property.StringProperty; 
import javafx.fxml.FXML; 
import javafx.fxml.Initializable; 
import javafx.scene.control.TableColumn; 
import javafx.scene.control.TableView; 
import javafx.scene.control.cell.PropertyValueFactory; 

/** 
* Main FXML Controller 
* @author Patrick Ott <[email protected]> 
* @version 1.0 
*/ 
public class MainController implements Initializable { 

    @FXML 
    TableView<Reservation> reservationTable; 

    @FXML 
    TableColumn<Reservation, Integer> resNumber; 

    @FXML 
    TableColumn<Reservation, String> customerName; 

    @FXML 
    TableColumn<Reservation, ObjectProperty<LocalDateTime>> checkIn; 

    @FXML 
    TableColumn<Reservation, ObjectProperty<LocalDateTime>> checkOut; 

    @Override 
    public void initialize(URL url, ResourceBundle rb) { 

     ReservationService service = new ReservationService(); 
     List<Reservation> allReservations = service.getAllReservations(); 
     reservationTable.getItems().addAll(allReservations); 
     resNumber.setCellValueFactory(new PropertyValueFactory<>("reserveNumber")); 
     customerName.setCellValueFactory(new PropertyValueFactory<>("customerName")); 
     checkIn.setCellValueFactory(new PropertyValueFactory<>("checkIn")); 
     checkOut.setCellValueFactory(new PropertyValueFactory<>("checkOut")); 
    } 


} 

Бронирование Entity

package de.professional_webworkx.reservationmanager.model; 

import java.time.LocalDate; 
import java.util.Random; 
import javafx.beans.property.IntegerProperty; 
import javafx.beans.property.ObjectProperty; 
import javafx.beans.property.SimpleIntegerProperty; 
import javafx.beans.property.SimpleObjectProperty; 
import javafx.beans.property.SimpleStringProperty; 
import javafx.beans.property.StringProperty; 

/** 
* Reservation entity 
* @author Patrick Ott <[email protected]> 
* @version 1.0 
*/ 
public class Reservation { 

    private IntegerProperty reserveNumberProperty; 
    private StringProperty customerNameProperty; 

    private ObjectProperty<LocalDate> checkIn; 
    private ObjectProperty<LocalDate> checkOut; 

    public Reservation() { 
     reserveNumberProperty = new SimpleIntegerProperty(generateReservationNumber()); 
     customerNameProperty = new SimpleStringProperty(); 
     checkIn     = new SimpleObjectProperty<>(); 
     checkOut    = new SimpleObjectProperty<>(); 
    } 

    public Reservation(final String customerName, final LocalDate checkIn, final LocalDate checkOut) { 
     reserveNumberProperty = new SimpleIntegerProperty(generateReservationNumber()); 
     customerNameProperty = new SimpleStringProperty(customerName); 
     this.checkIn   = new SimpleObjectProperty<>(checkIn); 
     this.checkOut   = new SimpleObjectProperty<>(checkOut); 
    } 

    /** 
    * @return the reserveNumberProperty 
    */ 
    public IntegerProperty getReserveNumberProperty() { 
     return reserveNumberProperty; 
    } 

    public Integer getReserveNumber() { 
     return reserveNumberProperty.get(); 
    } 

    /** 
    * @param reserveNumberProperty the reserveNumberProperty to set 
    */ 
    public void setReserveNumberProperty(IntegerProperty reserveNumberProperty) { 
     this.reserveNumberProperty = reserveNumberProperty; 
    } 

    /** 
    * @return the customerNameProperty 
    */ 
    public StringProperty getCustomerNameProperty() { 
     return customerNameProperty; 
    } 

    public String getCustomerName() { 
     return customerNameProperty.get(); 
    } 

    /** 
    * @param customerNameProperty the customerNameProperty to set 
    */ 
    public void setCustomerNameProperty(StringProperty customerNameProperty) { 
     this.customerNameProperty = customerNameProperty; 
    } 

    /** 
    * @return the checkIn 
    */ 
    public ObjectProperty<LocalDate> getCheckInProperty() { 
     return checkIn; 
    } 

    public LocalDate getCheckIn() { 
     return checkIn.getValue(); 
    } 

    /** 
    * @param fromProperty the checkIn to set 
    */ 
    public void setCheckInProperty(ObjectProperty<LocalDate> fromProperty) { 
     this.checkIn = fromProperty; 
    } 

    /** 
    * @return the checkOut 
    */ 
    public ObjectProperty<LocalDate> getCheckOutProperty() { 
     return checkOut; 
    } 

    public LocalDate getCheckOut() { 
     return checkOut.getValue(); 
    } 

    /** 
    * @param toProperty the checkOut to set 
    */ 
    public void setCheckOutProperty(ObjectProperty<LocalDate> toProperty) { 
     this.checkOut = toProperty; 
    } 

    private Integer generateReservationNumber() { 
     Random random = new Random(); 
     int nextInt = random.nextInt(); 
     return new Integer(nextInt); 
    } 
} 

ReservationService

package de.professional_webworkx.reservationmanager.business; 

import de.professional_webworkx.reservationmanager.model.Reservation; 
import java.time.LocalDate; 
import java.util.ArrayList; 
import java.util.List; 

/** 
* ReservationService 
* persist, query, delete, edit Reservations 
* @author Patrick Ott <[email protected]> 
* @version 1.0 
*/ 
public class ReservationService { 

    public ReservationService() { 
     super(); 
    } 

    public List<Reservation> getAllReservations() { 
     List<Reservation> reservations = new ArrayList<>(); 
     // fetch all reservations from database 
     reservations.add(new Reservation("Patrick", LocalDate.now(), LocalDate.now().plusWeeks(3))); 
     reservations.add(new Reservation("userXYZ", LocalDate.now(), LocalDate.now().plusWeeks(2))); 
     return reservations; 
    } 
} 

И начать его

package de.professional_webworkx.reservationmanager; 

import java.io.IOException; 
import javafx.application.Application; 
import javafx.fxml.FXMLLoader; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 
import javafx.stage.Stage; 

/** 
* 
* @author Patrick Ott <[email protected]> 
*/ 
public class ReservationManager extends Application { 

    @Override 
    public void start(Stage primaryStage) throws IOException { 

     Parent parent = FXMLLoader.load(getClass().getResource("main.fxml")); 

     Scene scene = new Scene(parent); 

     primaryStage.setTitle("Hotel Reservation Manager v1.0"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

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

} 
Смежные вопросы