1 回答

TA貢獻1784條經驗 獲得超7個贊
您需要CellFactory在ListView. 然后我們可以確定該單元格是否屬于List您用來填充Listview. 如果是這樣,請僅對該單元格應用不同的樣式。
我不知道是否有一種方法來確定第一小區的ListView,但我們一定可以捕捉在第一項List。
考慮以下應用程序。我們有一個ListView只顯示字符串列表的。
我們設置自定義CellFactory的ListView,并設置單元格樣式,如果item是在第一List填充ListView。
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple interface
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
// Create the ListView
ListView<String> listView = new ListView<>();
listView.getItems().setAll("Title", "One", "Two", "Three", "Four", "Five");
// Set the CellFactory for the ListView
listView.setCellFactory(list -> {
ListCell<String> cell = new ListCell<String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
// There is no item to display in this cell, so leave it empty
setGraphic(null);
// Clear the style from the cell
setStyle(null);
} else {
// If the item is equal to the first item in the list, set the style
if (item.equalsIgnoreCase(list.getItems().get(0))) {
// Set the background color to blue
setStyle("-fx-background-color: blue; -fx-text-fill: white");
}
// Finally, show the item text in the cell
setText(item);
}
}
};
return cell;
});
root.getChildren().add(listView);
// Show the Stage
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
結果
顯然,您需要進行一些調整以匹配您的數據模型,并且僅通過 a 進行匹配String
并不是最好的方法。
這不會阻止用戶選擇第一個項目,并且如果在構建場景后對列表進行排序,則可能無法按預期工作。
雖然這可能會回答您的直接問題,但為了確保為用戶提供良好的體驗,還需要考慮其他事項。
添加回答
舉報