我在使用 javafx 8 时遇到问题
我有一个已绑定(bind)到 .fxml 文件的 Controller 类。这是我的 Controller 类构造函数的开始。
public class SearchOverviewController {
@FXML
private TreeView<String> bookTree;
....
我尝试创建一个名为 BookTree 的自定义 TreeView 类。这是为了管理 TreeView 并添加子项等等。我想将该功能分离到此类中。
public class BookTree extends TreeView<String>{
TreeItem rootItem;
public BookTree() {
super();
initRootItem();
setupBookTree();
}
public void initRootItem(){
rootItem = new TreeItem<String> ("Hello");
this.setRoot(rootItem);
rootItem.setExpanded(true);
}
private void setupBookTree(){
String[] items = {"hello", "how", "are", "you"};
for(String s : items){
addChildItem(rootItem, s);
}
}
public void addChildItem(TreeItem localRootItem, String title){
localRootItem.setExpanded(true);
TreeItem<String> child = new TreeItem<String> (title);
localRootItem.getChildren().add(child);
}
public void getChildItem(String name){
//TODO implement
}
}
然后我将 SearchOverviewController 类修改为:
public class SearchOverviewController {
@FXML
private BookTree bookTree;
....
但是,当我尝试使用这些更改运行它时,我收到此错误:
Could not load resource because of: javafx.fxml.LoadException:
/D:/Code/workspace/ocean2/target/classes/com/zurg/ocean2/view/SearchOverview.fxml:20
这是我的 SearchOverview.fxml 供引用。错误指向以下行:TreeView fx:id="bookTree"maxWidth="300.0"
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<AnchorPane styleClass="background" stylesheets="@DarkTheme.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.zurg.ocean2.view.SearchOverviewController">
<children>
<HBox layoutX="15.0" layoutY="15.0" spacing="10.0" AnchorPane.leftAnchor="15.0" AnchorPane.rightAnchor="15.0" AnchorPane.topAnchor="15.0">
<children>
<TextField fx:id="searchField" onAction="#searchButtonAction" HBox.hgrow="SOMETIMES" />
<Button mnemonicParsing="false" onAction="#searchButtonAction" text="Search" />
</children>
</HBox>
<Separator prefHeight="4.0" prefWidth="200.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="64.0" />
<SplitPane dividerPositions="0.5" prefHeight="160.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="68.0">
<items>
<TreeView fx:id="bookTree" maxWidth="300.0">
<effect>
<MotionBlur />
</effect></TreeView>
<TextArea fx:id="textArea" prefHeight="200.0" prefWidth="200.0" />
</items>
</SplitPane>
</children>
</AnchorPane>
我真的很困惑为什么我无法创建自定义 JavaFX 类。我什至尝试创建一个管理器类,它将 TreeView 作为参数并对其进行修改,类似于当前将我的自定义 BookTree 设置为相同的错误消息。
感谢您的帮助!
最佳答案
<TreeView ...>
指示FXMLLoader
实例化 TreeView
。 fx:id
尝试将其分配给声明为的字段
private BookView bookTree ;
在普通 Java 中,这类似于尝试调用
private BookTree bookTree = new TreeView<?>();
这显然会在编译时失败。
您应该能够将 FXML 更改为
<BookTree fx:id="bookTree" maxWidth="300.0"/>
关于java - 自定义 JavaFX 8 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345997/