【发布时间】:2021-05-09 18:10:00
【问题描述】:
我一直在努力为可编辑的ComboBox 实现一个事件侦听器,它会将已编辑的项目添加到应用程序列表的末尾,但是当提交已编辑的项目时会抛出IndexOutOfBoundsException。我不明白为什么会这样。
因此,我创建了一个简化的应用程序,如下所示,并尝试将添加编辑项的代码包含在 Platform.runLater() 块中,但问题仍然存在。
任何人都可以建议可能导致此异常的原因吗?
非常感谢。
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class ComboBoxTest extends Application {
ComboBox<String> cbItems;
Label lblResponse;
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
stage.setTitle("ComboBox Demo");
FlowPane root = new FlowPane(10, 10);
root.setAlignment(Pos.TOP_CENTER);
Scene scene = new Scene(root, 240, 120);
stage.setScene(scene);
lblResponse = new Label();
ObservableList<String> items =
FXCollections.observableArrayList("item1", "item2", "item3", "item4", "item5");
cbItems = new ComboBox<String>(items);
cbItems.setValue("item1");
cbItems.setEditable(true);
lblResponse.setText("Selected item is " + cbItems.getValue());
// Listen for action events on the combo box.
cbItems.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent ae) {
lblResponse.setText("Selected item is " + cbItems.getValue());
//add the modified item to the end of the list
int i = cbItems.getSelectionModel().getSelectedIndex();
if(!items.get(i).equals(cbItems.getValue())){
items.add(cbItems.getValue());
}
}
});
root.getChildren().addAll(cbItems, lblResponse);
stage.show();
}
}
【问题讨论】:
-
欢迎来到 StackOverflow!第一个问题好!您甚至可以通过添加确切的错误消息和堆栈跟踪来改进它。