gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:29 25 4
gpt4 key购买 nike

这是使用 javaFX 的聊天应用程序的界面。聊天窗口是一个 ListView 组件,我正在使用 CSS 对其进行一些修饰。这是 CSS 和屏幕截图: enter image description here

.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/分隔符的东西...)

最佳答案

使用将图形设置为 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;
}

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

enter image description here

这是一个更完整的 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 ;
}

enter image description here

关于css - 在 JavaFX 中动态更改 ListCell 的 ListView 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40830709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com