使用FXML定制JavaFX中的ListView

37

我想在JavaFX中制作自定义列表视图。这里我需要将多个组件绑定在列表单元格中,例如:一个标签、一个文本字段、一个按钮放在一个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>

1
你尝试过使用Cell Factory来创建ListView吗?请参考https://dev59.com/5mgv5IYBdhLWcg3wTvA-#10700642。 - Uluk Biy
3个回答

87

我理解你的问题。在 Listview 中有主要两种设置项的方式:

1. 创建 ObservableList 并使用 ObservableList 来设置 ListView 的项 (listView.setItems(observableList))。

2. 使用 ListView 类的 setCellFactory() 方法。

你会更倾向于使用 setCellFactory() 方法,因为这种方法简化了过程并帮助将业务逻辑和 UI(FXML)分离。


以下是更详细的说明:


1. 创建一个名为listview.fxml的新FXML文件以包含 ListView,并将 ListViewController 类设置为其控制器:

文件:listview.fxml:

<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.ListView?>
<?import demo.ListViewController?>

<GridPane xmlns:fx="http://javafx.com/fxml" alignment="CENTER">
     <ListView fx:id="listView"/>
</GridPane>

2. 创建控制器并将其命名为 ListViewController
控制器可以加载 listview.fxml 文件并访问 listview

文件: ListViewController.java:


package demo;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.util.Callback;
import java.io.IOException;
import java.util.Set;

public class ListViewController
{
    @FXML
    private ListView listView;
    private Set<String> stringSet;
    ObservableList observableList = FXCollections.observableArrayList();

    public ListViewController()
    {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/listview.fxml"));
        fxmlLoader.setController(this);
        try
        {
            Parent parent = (Parent)fxmlLoader.load();
            Scene scene = new Scene(parent, 400.0 ,500.0);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    public void setListView()
    {
        stringSet.add("String 1");
        stringSet.add("String 2");
        stringSet.add("String 3");
        stringSet.add("String 4");
        observableList.setAll(stringSet);
        listView.setItems(observableList);
        listView.setCellFactory(new Callback<ListView<String>, javafx.scene.control.ListCell<String>>()
        {
            @Override
            public ListCell<String> call(ListView<String> listView)
            {
                return new ListViewCell();
            }
        });
    }
}

3. 首先,您需要设置ObservableList的值。这非常重要。
然后,使用ObservableList设置列表项,并在ListView上调用setCellFactory()方法。在给定的示例中,我只是将String值添加到String集合中(Set<String> stringSet)。


4. 当在ListView上调用setCellFactory()方法时,它将返回ListCell。为了简单起见,我添加了一个扩展ListCell的类,并且ListCell()中有setGraphic()方法,将为ListCell设置项目。

文件:ListViewCell.java

package demo;

import javafx.scene.control.ListCell;

public class ListViewCell extends ListCell<String>
{
    @Override
    public void updateItem(String string, boolean empty)
    {
        super.updateItem(string,empty);
        if(string != null)
        {
            Data data = new Data();
            data.setInfo(string);
            setGraphic(data.getBox());
        }
    }
}

5. 我刚刚添加了一个类,它将加载listCellItem.fxml并返回HBox,该HBox将包含其他组件作为子项。
然后将HBox设置为ListCell

文件:listCellItem.fxml

 <?import demo.Data?>
 <?import javafx.scene.layout.HBox?>
 <?import javafx.scene.control.Label?>

<HBox xmlns:fx="http://javafx.com/fxml" fx:id="hBox">
<children>
    <Label  fx:id="label1"/>
    <Label  fx:id="label2"/>
</children>
</HBox>

文件:Data.java

package demo;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import java.io.IOException;

public class Data
{
    @FXML
    private HBox hBox;
    @FXML
    private Label label1;
    @FXML
    private Label label2;

    public Data()
    {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/listCellItem.fxml"));
        fxmlLoader.setController(this);
        try
        {
            fxmlLoader.load();
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    public void setInfo(String string)
    {
        label1.setText(string);
        label2.setText(string);
    }

    public HBox getBox()
    {
        return hBox;
    }
}

使用这种方式,您可以使用setCellFactory()方法分离业务逻辑和FXML。

希望这对您有所帮助。


4
此答案最适用于使用MVC设计的JavaFX应用程序。 - shambhu
1
嘿,谢谢Anvay,我正期待着你在这里提到的完全相同的组件。非常感谢。 - Santosh Biswakarma
8
这确实有效。尽管在listcell类上使用updateItem存在问题。每次调用该方法时都不应该“膨胀”FXML。考虑在ListCell的构造函数中创建一个Data对象,并仅在updateItem方法中更新其内容(仅膨胀一次)。 - couceirof
1
如何在运行时向自定义列表视图中添加新项? - Roshan Sharma
1
我猜 fxmlLoader.load(); 应该被替换成 hBox = fxmlLoader.load(); - AljoSt
显示剩余2条评论

6
上面的示例需要进行一些调整才能正常工作。这些都是简单的事情,可以轻松解决。
  1. ListViewController 需要在 JavaFX 应用程序线程上运行。
  2. 只能从 JavaFX 的 initialize() 方法中调用注入的 @FXML 元素。
  3. 需要调用 setListView()。
  4. 在调用 setListView() 之前,需要使用 new 为示例中的 stringSet 分配内存。
下面的 ListViewController 在进行这些更改后可以正常工作。我将 "stringSet" 更改为列表 "stringList"。控制器基本上是由 Scene Builder 2 提供的示例控制器。
 public class ListViewController 
 {

     @FXML private   ResourceBundle      resources;

     @FXML private   URL                 location;

     @FXML private   ListView            listView;

     private         List<String>        stringList     = new ArrayList<>(5);
     private         ObservableList      observableList = FXCollections.observableArrayList();

     public void setListView(){

         stringList.add("String 1");
         stringList.add("String 2");
         stringList.add("String 3");
         stringList.add("String 4");

         observableList.setAll(stringList);

         listView.setItems(observableList);

         listView.setCellFactory(
             new Callback<ListView<String>, javafx.scene.control.ListCell<String>>() {
                 @Override
                 public ListCell<String> call(ListView<String> listView) {
                     return new ListViewCell();
                 }
             });
     }

     @FXML
     void initialize() {
         assert listView != null : "fx:id=\"listView\" was not injected: check your FXML file 'CustomList.fxml'.";

         setListView();
     }

 }//ListViewController

JavaFX平台需要在JavaFX应用程序的main()方法中启动。Netbeans方便地提供了大部分结构,从Maven JavaFX应用程序模板开始。

public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {

        Parent root = FXMLLoader.load(getClass().getResource("/fxml/CustomList.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add("/styles/Styles.css");

        stage.setTitle("CustomList");
        stage.setScene(scene);
        stage.show();
    }

    /**
     *  The main() method is ignored in correctly deployed JavaFX application.
     * 
     *  @param args the command line arguments
     **/
    public static void main(String[] args) {

        launch(args);
    }
}

2

Anvay的答案对我来说出了一些问题,为了解决它,我只需要做一些非常小的调整:

  1. remove import data statement from listCellItem.fxml
  2. as the comment below the post states in Data.java put hBox = fmxlLoader.load()
  3. I also had a main class (intellij auto generated).

    public class MainMain extends Application {
    
    @Override
    public void start(Stage primaryStage) throws Exception{
    
    FXMLLoader fxmlLoader = new 
    FXMLLoader(getClass().getResource("MainController.fxml"));
    try
    {
        Parent root = fxmlLoader.load();
    
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Title");
        primaryStage.show();
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
    }
    
    
    
    public static void main(String[] args) {
        launch(args);
    }
    

我知道对于大部分专家来说这可能很显然,但是在我调试代码的时候这些问题困扰了我好几个小时。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接