使用單元工廠將圖形設置爲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 ;
}
你的意思是你想列表出現鋸齒?根據行中文本的長度,右邊緣位於不同的位置? – Itai
再次看我意識到你的意思是正文,而不是左側的用戶列表,這樣更有意義。 我相信列表單元忽略所有的大小,因爲它是由'ListView'佈局的,所以你可能不得不提供一個自定義的單元工廠並且設計內部節點的樣式(例如'TextFlow')。 – Itai