gpt4 book ai didi

java - JavaFX 中每一行都带有删除按钮的 ListView

转载 作者:搜寻专家 更新时间:2023-11-01 03:17:45 24 4
gpt4 key购买 nike

如何在 JavaFX 中创建每行都带有删除按钮和删除按钮操作的 ListView

enter image description here

最佳答案

这是一个主要基于this anwer的SSCE .

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SO extends Application {
static class XCell extends ListCell<String> {
HBox hbox = new HBox();
Label label = new Label("");
Pane pane = new Pane();
Button button = new Button("Del");

public XCell() {
super();

hbox.getChildren().addAll(label, pane, button);
HBox.setHgrow(pane, Priority.ALWAYS);
button.setOnAction(event -> getListView().getItems().remove(getItem()));
}

@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);

if (item != null && !empty) {
label.setText(item);
setGraphic(hbox);
}
}
}

@Override
public void start(Stage primaryStage) throws Exception {
StackPane pane = new StackPane();
Scene scene = new Scene(pane, 300, 150);
primaryStage.setScene(scene);
ObservableList<String> list = FXCollections.observableArrayList(
"Item 1", "Item 2", "Item 3", "Item 4");
ListView<String> lv = new ListView<>(list);
lv.setCellFactory(param -> new XCell());
pane.getChildren().add(lv);
primaryStage.show();
}

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

最重要的修改是这一行

button.setOnAction(event -> getListView().getItems().remove(getItem()));

此单元格代表的项目已从 ListView 的项目列表中删除。

关于java - JavaFX 中每一行都带有删除按钮的 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42529782/

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