gpt4 book ai didi

java - 从 UI 向组合框添加值?

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

如何才能向组合框中的项目添加值,以便用户可以从现有项目中进行选择,也可以选择“添加元素”项目来添加新项目?

private ComboBox<String> comboStructDonnees;

随后:

comboData.getItems().addAll("TVW", "VWT", "TTVW", "VWXT", "Add item");

我不知道接下来应该创建哪个事件,如果可能的话,我希望在添加的元素上输入文本。

如有任何帮助,我们将不胜感激。

最佳答案

您可以将具有“特殊值”(例如空字符串)的项目添加到组合框项目列表的末尾。

使用单元工厂创建一个单元,该单元在显示该值时向用户显示用户友好的消息(例如“添加项目..”)。将事件过滤器添加到单元格,如果单元格显示特殊值,该单元格将显示一个用于输入新值的对话框。

这是一个快速 SSCCE:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.TextInputDialog;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class AddItemToComboBox extends Application {

@Override
public void start(Stage primaryStage) {
ComboBox<String> combo = new ComboBox<>();
combo.getItems().addAll("One", "Two", "Three", "");
combo.setCellFactory(lv -> {
ListCell<String> cell = new ListCell<String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
if (item.isEmpty()) {
setText("Add item...");
} else {
setText(item);
}
}
}
};

cell.addEventFilter(MouseEvent.MOUSE_PRESSED, evt -> {
if (cell.getItem().isEmpty() && ! cell.isEmpty()) {
TextInputDialog dialog = new TextInputDialog();
dialog.setContentText("Enter item");
dialog.showAndWait().ifPresent(text -> {
int index = combo.getItems().size()-1;
combo.getItems().add(index, text);
combo.getSelectionModel().select(index);
});
evt.consume();
}
});

return cell ;
});

BorderPane root = new BorderPane();
root.setTop(combo);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}

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

enter image description here enter image description here enter image description here

关于java - 从 UI 向组合框添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43926994/

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