簡體   English   中英

如何將自定義類正確導入此FXML文件?

[英]How do I import my custom class correctly into this FXML file?

我正在制作一個簡單的食譜應用程序來練習JavaFX,但是遇到了問題。 我似乎無法導入此類:

package application;

import javafx.beans.property.SimpleStringProperty;

public class Recipe {
   private final SimpleStringProperty Name = new SimpleStringProperty("");

   public Recipe() {
        this("");
    }

    public Recipe(String recipeName) {
        setRecipeName(recipeName);

    }

    public String getRecipeName() {
        return Name.get();
    }

    public void setRecipeName(String rName) {
        Name.set(rName);
    }

}

進入此FXML視圖文件:

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

<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.cell.*?>
<?import javafx.collections.*?>
<?import fxmltableview.*?>
<?import java.lang.String?>
<?import application.Recipe ?>


<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <TableView prefHeight="400.0" prefWidth="600.0">
        <columns>
          <TableColumn prefWidth="599.0" text="Column One" >
          <cellValueFactory><PropertyValueFactory property="Name" />
         </cellValueFactory>
          </TableColumn>
        </columns>
        <items>
    <FXCollections fx:factory="observableArrayList">
        <Recipe Name="Test Name"/>
    </FXCollections>
        </items>
      </TableView>
   </children>
</AnchorPane>

我不斷收到錯誤消息。 任何幫助是極大的贊賞。

好的,事實證明我無法將字段命名為“名稱”,因為它顯然是指FXCollections中的某些內容(我認為),因此我將屬性更改為recipeName,這似乎可以解決問題。

Java中的屬性名稱由方法名稱而不是字段名稱確定。 由於您的Recipe類定義了方法getRecipeName()setRecipeName(...) ,因此屬性名稱為recipeName 因此,您需要

 <Recipe recipeName="Test Name"/>

您可以根據自己的喜好為該字段命名-不會影響屬性名稱的含義。 但是,優良作法是遵循標准命名約定並使字段名稱以小寫開頭。 在JavaFX中定義屬性訪問器方法也很有用。 這是一個例子:

public class Recipe {
   private final SimpleStringProperty name = new SimpleStringProperty("");

   public Recipe() {
        this("");
    }

    public Recipe(String recipeName) {
        setRecipeName(recipeName);

    }

    public String getRecipeName() {
        return name.get();
    }

    public void setRecipeName(String rName) {
        name.set(rName);
    }

    public StringProperty recipeNameProperty() {
        return name ;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM