2013-11-23 2 views
2

Мне было так сложно попробовать и получить ответ для этого. Почему-то Oracle не документирует на своем сайте ?! Он уже задан в stackoverflow (JavaFX: TableView(fxml) filling with data и JavaFX FXML table; why won't my data display), но когда я пытаюсь воссоздать с ответами, я все еще не могу заставить его работать. Я был бы чрезвычайно благодарен, если кто-то сможет помочь! Я выпью весь код из них.Данные таблицы заполнения с помощью javafx с использованием fxml

public class Heroes extends Application { 

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

    @Override 
    public void start(Stage primaryStage) throws Exception { 
     try { 
      AnchorPane page = FXMLLoader.load(Heroes.class.getResource("FXMLDocument.fxml")); 

      Scene scene = new Scene(page); 
      primaryStage.setScene(scene); 
      primaryStage.setTitle("Sample Window"); 
      primaryStage.setResizable(false); 
      primaryStage.show(); 
     } catch (Exception e) { 
     } 
    } 
} 

public class FXMLDocumentController implements Initializable { 

    /** 
    * Initializes the controller class. 
    */ 
    @FXML 
    TableView<Table> tableID; 
    @FXML 
    TableColumn<Table, Integer> tID; 
    @FXML 
    TableColumn<Table, String> tName; 
    @FXML 
    TableColumn<Table, String> tDate; 
    @FXML 
    TableColumn<Table, String> tPrice; 
    int iNumber = 1; 
    ObservableList<Table> data = 
      FXCollections.observableArrayList(
      new Table(iNumber++, "Superman", "12/02/2013", "20"), 
      new Table(iNumber++, "Batman", "2/02/2013", "40"), 
      new Table(iNumber++, "Aquaman", "1/02/2013", "100"), 
      new Table(iNumber++, "The Flash", "12/02/2013", "16")); 

    @Override 
    public void initialize(URL url, ResourceBundle rb) { 
     // System.out.println("called"); 

     tID.setCellValueFactory(new PropertyValueFactory<Table, Integer>("rID")); 
     tName.setCellValueFactory(new PropertyValueFactory<Table, String>("rName")); 
     tDate.setCellValueFactory(new PropertyValueFactory<Table, String>("rDate")); 
     tPrice.setCellValueFactory(new PropertyValueFactory<Table, String>("rPrice")); 
     tableID.setItems(data); 

    } 
} 

public class Table { 

    SimpleIntegerProperty rID; 
    SimpleStringProperty rName; 
    SimpleStringProperty rDate; 
    SimpleStringProperty rPrice; 

    public Table(int rID, String rName, String rDate, String rPrice) { 
     this.rID = new SimpleIntegerProperty(rID); 
     this.rName = new SimpleStringProperty(rName); 
     this.rDate = new SimpleStringProperty(rDate); 
     this.rPrice = new SimpleStringProperty(rPrice); 
     System.out.println(rID); 
     System.out.println(rName); 
     System.out.println(rDate); 
     System.out.println(rPrice); 
    } 

    public Integer getrID() { 
     return rID.get(); 
    } 

    public void setrID(Integer v) { 
     this.rID.set(v); 
    } 

    public String getrDate() { 
     return rDate.get(); 
    } 

    public void setrDate(String d) { 
     this.rDate.set(d); 
    } 

    public String getrName() { 
     return rName.get(); 
    } 

    public void setrName(String n) { 
     this.rDate.set(n); 
    } 

    public String getrPrice() { 
     return rPrice.get(); 
    } 

    public void setrPrice(String p) { 
     this.rPrice.set(p); 
    } 
} 
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="heroes.FXMLDocumentController"> 
    <children> 
    <SplitPane dividerPositions="0.535175879396985" focusTraversable="true" orientation="VERTICAL" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"> 
     <items> 
     <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0"> 
      <children> 
      <TableView fx:id="tableID" prefHeight="210.0" prefWidth="598.0" tableMenuButtonVisible="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"> 
       <columns> 
       <TableColumn minWidth="20.0" prefWidth="40.0" text="ID" fx:id="tID" > 
        <cellValueFactory> 
         <PropertyValueFactory property="tID" /> 
        </cellValueFactory> 
       </TableColumn> 
       <TableColumn prefWidth="100.0" text="Date" fx:id="tDate" > 
        <cellValueFactory> 
         <PropertyValueFactory property="tDate" /> 
        </cellValueFactory> 
       </TableColumn> 
       <TableColumn prefWidth="200.0" text="Name" fx:id="tName" > 
        <cellValueFactory> 
         <PropertyValueFactory property="tName" /> 
        </cellValueFactory> 
       </TableColumn> 
       <TableColumn prefWidth="75.0" text="Price" fx:id="tPrice" > 
        <cellValueFactory> 
         <PropertyValueFactory property="tPrice" /> 
        </cellValueFactory> 
       </TableColumn> 
       </columns> 
      </TableView> 
      </children> 
     </AnchorPane> 
     <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0" /> 
     </items> 
    </SplitPane> 
    </children> 
</AnchorPane> 
+0

Кроме того, когда приложение загружается, зависание над линией становится синим, где предполагается, что это поля, и ничего не происходит там, где их нет. Таким образом, похоже, что предполагается, что данные будут отображаться в этих строках, но не отображаются. Не уверен, что это помогает. Благодарю. – user3023715

ответ

1

PropertyValueFactory пытается найти свои значения данных двумя способами:

1) Поиск метода, например, nameProperty где name - это то, что вы указываете в конструкторе, например, в вашем примере. «РИД».

Таким образом, вы должны Способы имени, как это (имя поля + «Property»):

public IntegerProperty rIDProperty() { 
    return rID; 
} 

И аналогично для других свойств.

2) Если они отсутствуют, он ищет методы, названные, например. getName где Name - это то, что вы указываете в конструкторе с первой буквой с заглавной буквы (согласно соглашению Java Beans).

В вашем примере у вас нет 1), но у вас есть 2) - но вы не заглавили первую букву имени свойства в геттерах и сеттерах!

Измените их, например.

public Integer getRID() { 
    return rID.get(); 
} 

И аналогичный.

Вам нужно либо 1), либо 2), но было бы хорошей практикой иметь оба.

Также обратите внимание, что проблема не связана с FXML каким-либо образом.

+0

Благодарим за помощь! :) – user3023715