gpt4 book ai didi

java - JavaFX 中带有自定义内容的 ListView

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:58:39 25 4
gpt4 key购买 nike

我如何使用 JavaFx 为我的应用制作自定义 ListView。我需要带图像的 HBox 和每行 listView 的 2 个标签。 enter image description here

最佳答案

您可以通过查看 ListView.setCellFactory(...) 提供自定义 CellFactory

Example

工作示例

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Callback;

public class CustomListView extends Application {
private static class CustomThing {
private String name;
private int price;
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public CustomThing(String name, int price) {
super();
this.name = name;
this.price = price;
}
}

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

@Override
public void start(Stage primaryStage) {
ObservableList<CustomThing> data = FXCollections.observableArrayList();
data.addAll(new CustomThing("Cheese", 123), new CustomThing("Horse", 456), new CustomThing("Jam", 789));

final ListView<CustomThing> listView = new ListView<CustomThing>(data);
listView.setCellFactory(new Callback<ListView<CustomThing>, ListCell<CustomThing>>() {
@Override
public ListCell<CustomThing> call(ListView<CustomThing> listView) {
return new CustomListCell();
}
});

StackPane root = new StackPane();
root.getChildren().add(listView);
primaryStage.setScene(new Scene(root, 200, 250));
primaryStage.show();
}

private class CustomListCell extends ListCell<CustomThing> {
private HBox content;
private Text name;
private Text price;

public CustomListCell() {
super();
name = new Text();
price = new Text();
VBox vBox = new VBox(name, price);
content = new HBox(new Label("[Graphic]"), vBox);
content.setSpacing(10);
}

@Override
protected void updateItem(CustomThing item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty) { // <== test for null item and empty parameter
name.setText(item.getName());
price.setText(String.format("%d $", item.getPrice()));
setGraphic(content);
} else {
setGraphic(null);
}
}
}

}

关于java - JavaFX 中带有自定义内容的 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27438629/

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