gpt4 book ai didi

listview - JavaFX - 带有图像按钮的 ListView 项目

转载 作者:行者123 更新时间:2023-12-02 15:17:12 24 4
gpt4 key购买 nike

我想知道是否可以在每个 ListView 项之后添加一个图像按钮。例如:sample

那些红色方 block 应该有一个按钮。如果可能的话,我该如何处理项目按钮的点击事件?

编辑:如果有其他控件可以做到这一点,请告诉我。我正在测试 TableView。

提前致谢!

最佳答案

我最近正在测试这个。我的解决方案:

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
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;
import javafx.util.Callback;

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

public XCell() {
super();
hbox.getChildren().addAll(label, pane, button);
HBox.setHgrow(pane, Priority.ALWAYS);
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println(lastItem + " : " + event);
}
});
}

@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(null); // No text in label of super class
if (empty) {
lastItem = null;
setGraphic(null);
} else {
lastItem = item;
label.setText(item!=null ? item : "<null>");
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(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
pane.getChildren().add(lv);
primaryStage.show();
}

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

单元格将如下所示:

Custom List Cell with Button

相关部分是 XCell.updateItem 方法和 setGraphic 调用。使用 setGraphic() 通常应为标签设置图标,但设置复杂节点同样有效 - 在本例中为带有标签和按钮的 HBox。

您需要确保按钮的事件处理程序引用列表中的正确项目。在下面的第一个链接中,提到当前选择的项目目前可能就足够了。因此,在处理按钮事件时,请获取列表中当前选定的索引。

您可能想看看这些:

关于listview - JavaFX - 带有图像按钮的 ListView 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15661500/

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