在 JavaFX 中动态更改 ListCell 的 ListView 宽度

Dynamically change ListCell's width of ListView in JavaFX

这是使用 javaFX 的聊天应用程序的界面。聊天 window 是一个 ListView 组件,我正在使用 CSS 对其进行一些润色。这是 CSS 和屏幕截图:

.list-cell {
  display: inline-block;
  -fx-min-width: 50px;
  -fx-background-color: lightyellow;
  -fx-background-radius: 30px;
  -fx-border-radius: 20px;
  -fx-border-width: 2px;
  -fx-border-style: solid;
  -fx-border-color: #666666;
}
.list-cell:empty {
  -fx-background-color: transparent;
  -fx-border-width: 0px;
}

问题是我想根据文本的长度更改每个 listCell 的宽度。我尝试在 CSS 文件中或使用 listView.setCellFactory 设置 minWidth prefWidth(例如 50px),但没有任何反应。长度完全没有变化。我想知道我是否可以像那样更改 listView 中每个单元格的长度(或者为了做到这一点,我必须使用类似 HBox/VBox/seperator...)

使用将图形设置为 Label 的细胞工厂,并设置标签的样式。例如:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

public class FormattedListCell extends Application {

    @Override
    public void start(Stage primaryStage) {
        ListView<String> listView = new ListView<>();
        listView.getItems().addAll("One", "Two", "Three", "Four");

        listView.setCellFactory(lv -> new ListCell<String>() {
            private final Label label = new Label();
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    label.setText(item);
                    setGraphic(label);
                }
            }
        });

        Scene scene = new Scene(listView, 400, 400);
        scene.getStylesheets().add("formatted-list-cell.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

并修改样式表:

.list-cell .label {
  display: inline-block;
  -fx-min-width: 50px;
  -fx-background-color: lightyellow;
  -fx-background-radius: 30px;
  -fx-border-radius: 20px;
  -fx-border-width: 2px;
  -fx-border-style: solid;
  -fx-border-color: #666666;
}
.list-cell:empty .label {
  -fx-background-color: transparent;
  -fx-border-width: 0px;
}

您可能需要实际设置列表单元格(以及其中的标签)的样式以获得您想要的确切样式,但这应该能让您入门。

这是一个更完整的 CSS 文件,它使用 -fx-background 使文本颜色自动调整,管理选择颜色,并为列表单元格本身添加一些样式:

.list-cell {
    -fx-background-color: transparent ;
    -fx-padding: 0 ;
}

.list-cell .label {
  display: inline-block;
  -fx-background: lightyellow;
  -fx-background-color: -fx-background ;
  -fx-background-radius: 30px;
  -fx-border-radius: 20px;
  -fx-border-width: 2px;
  -fx-border-style: solid;
  -fx-border-color: #666666;
  -fx-padding: 12px ;
}
.list-cell:empty .label {
  -fx-background-color: transparent;
  -fx-border-width: 0px;
}
.list-cell:selected .label {
    -fx-background: -fx-selection-bar ;
}