2017-07-17 74 views
1

我正在制作一个简单的食谱应用程序来练习JavaFX,我遇到了一个问题。我似乎无法导入这个类:如何正确导入我的自定义类到这个FXML文件中?

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> 

我一直就行收到一个错误。任何帮助是极大的赞赏。

+0

嗨, 我不知道,如果解决您的问题(我想不会,SRY),但命名您的变量“名称”(首字母大写)被认为是不好风格,并可能被编译器误解。 (至少据我所知...) – GoatyGuy

+0

是的,这并没有真正帮助我,但你是对的,我改变它为recipeName,这是更明显的,但...我仍然无法得到它工作。编辑:没关系,这是命名约定。名称显然指的是...中的保留字段,我不知道,但现在起作用。 – JLH

回答

0

Java中的属性名称由方法名称决定,而不是字段名称。由于您的Recipe类定义了方法getRecipeName()setRecipeName(...),因此属性名称为recipeName。因此,你需要

<Recipe recipeName="Test Name"/> 

可以命名字段任何你喜欢的 - 它不会影响什么属性名被认为是。但是,最好遵循standard naming conventions并使字段名称开始小写。在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 ; 
    } 

} 
0

好吧,事实证明我无法命名字段“名称”,因为它显然是指FXCollections中的某些内容(我认为),所以我将属性更改为recipeName,似乎解决了问题。

+0

一个会喜欢;) – GoatyGuy

+0

这根本不是问题。问题在于,类中的属性名是'recipeName'(因为你有'getRecipeName'和'setRecipeName')方法,但是在FXML中你试图引用一个名为'Name'的属性(所以FXMLLoader会尝试找到一个名为'setName'的方法,它不存在)。 –

相关问题