我想在javafx中创建自定义列表视图 . 在这里,我需要在列表单元格中绑定多个组件,如下所示,如一个标签,一个文本字段,一个HBox下的一个按钮和两个按钮,一个超链接,另一个HBox中的一个标签,这些HBox属于一个VBox,这个VBox属于单个列表单元格,它将重复并生成一个列表视图 .
代码是
<ListView fx:id="ListView" layoutX="0" layoutY="30" prefWidth="600" prefHeight="300">
<HBox fx:id="listBox" alignment="CENTER_LEFT">
<padding><Insets top="5" bottom="5" left="5"></Insets> </padding>
<HBox alignment="CENTER_LEFT" prefWidth="170" minWidth="88">
<Label fx:id="surveyName" text="Field A" styleClass="Name"></Label>
</HBox>
<VBox styleClass="Description" prefWidth="155" minWidth="86">
<HBox>
<HBox styleClass="surveyDesIcon" prefWidth="20" prefHeight="16"></HBox>
<Label fx:id="surveyCode" text="PRW3456HJ"></Label>
</HBox>
<HBox>
<HBox styleClass="DateIcon" prefWidth="20" prefHeight="16"></HBox>
<Label fx:id="Date" text="PRW3456HJ"></Label>
</HBox>
</VBox>
<HBox fx:id="Status" prefWidth="160" minWidth="80">
<Label fx:id="StatusLabel" text="Checking Files.."/>
</HBox>
<HBox fx:id="StatusIcon1" prefWidth="50" prefHeight="50" alignment="CENTER">
<Label styleClass="StatusIcon1" prefWidth="24" prefHeight="24" alignment="CENTER"/>
</HBox>
<HBox fx:id="StatusIcon2" prefWidth="50" prefHeight="50" styleClass="StatusIconBox" alignment="CENTER">
<Hyperlink styleClass="StatusIcon2" prefWidth="24" maxHeight="24" alignment="CENTER"/>
</HBox>
</HBox>
</ListView>
3 回答
由于某种原因,Anvay的答案对我没有用,我必须做的就是修复它只是一些非常小的调整:
从listCellItem.fxml中删除import data语句
作为Data.java中post状态下面的注释放入hBox = fmxlLoader.load()
我还有一个主类(intellij auto generated) .
我知道这对大多数专家来说可能是显而易见的,但这些问题在我调试时困扰了我好几个小时 .
我理解你的问题 . 在_531682中设置项目主要有两种方法:
1. 创建
ObservableList
并使用ObservableList
(listView.setItems(observableList)
)设置ListView
的项目 .2. 使用
ListView
类的setCellFactory()
方法 .您更愿意使用
setCellFactory()
方法,因为这种方法简化了流程,并且有助于分离业务逻辑和UI(FXML) .Here is a more detailed explaination:
1. 创建一个名为
listview.fxml
的新FXML文件以包含ListView
,并将ListViewController
类设置为其控制器:文件:listview.fxml:
2. 创建控制器并将其命名为
ListViewController
.控制器可以加载
listview.fxml
文件并访问listview
.文件:ListViewController.java:
3. 首先,您需要设置
ObservableList
的值 . This is very important.然后,使用
ObservableList
设置列表项,并在ListView
上调用setCellFactory()
方法 . 在给定的示例中,我只需将String
值添加到String
集(Set<String> stringSet
) .4. 在
ListView
上调用setCellFactory()
方法时,它将返回ListCell
. 因此,为了简单起见,我添加了一个扩展ListCell
的类,并且setGraphic()
方法适用于ListCell()
并将设置ListCell
的项目 .文件:ListViewCell.java:
5. 我刚刚添加了一个类,它将加载
listCellItem.fxml
并返回HBox
,它将包含其他组件作为子项 .然后将
HBox
设置为ListCell
.文件:listCellItem.fxml:
文件:Data.java:
使用这种方式,您可以使用
setCellFactory()
方法分离业务逻辑和FXML .希望这有用 .
@ Anvay 上面的例子需要进行一些调整才能工作 . 这些都是设置在轨道上的简单方法 .
ListViewController需要在JavaFX应用程序线程上运行 .
您只能从JavaFX initialize ()方法调用注入的@FXML元素
需要调用setListView()
示例中的stringSet需要在调用setListView()之前使用new分配 .
下面的ListViewController可以处理这些更改 . 我改变了“stringSet " to a list, " stringList” . 控制器几乎是 Scene Builder 2提供的样本控制器
需要从JavaFX应用程序的main()方法启动JavaFX平台 . Netbeans从Maven JavaFX应用程序模板中提供了大部分结构 .