【发布时间】:2018-08-23 19:36:56
【问题描述】:
我正在尝试制作一个 JavaFX ComboBox 来记住用户输入的条目的历史记录。添加新项目有效,但从下拉列表中选择无效。
简而言之,我正在尝试控制
- 将最近输入的条目添加到顶部,作为
ComboBox的第一项。 - 为下一个条目清除
TextField部分。 - 从
ComboBox中选择项目后,会将选择复制到TextField,而不修改ComboBox的项目。
添加新项目可以正常工作,但将以前的条目复制到该字段会令人沮丧。
我能找到的唯一类似问题是javafx combobox items list issue,不幸的是,他的解决方案没有解决我的问题。
代码
import java.util.LinkedList;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ComboBox;
public class HistoryField<String> extends ComboBox<String> {
public final static int DEFAULT_MAX_ENTRIES = 256;
//Data members
private int maxSize;
private final ObservableList<String> history;
//Default constructor
public HistoryField() {
this(DEFAULT_MAX_ENTRIES, (String[]) null);
}
public HistoryField(int maxSize, String ... entries) {
super(FXCollections.observableList(new LinkedList<>()));
this.setEditable(true);
this.maxSize = maxSize;
this.history = this.getItems();
//Populate list with entries (if any)
if (entries != null) {
for (int i = 0; ((i < entries.length) && (i < this.maxSize)); i++) {
this.history.add(entries[i]);
}
}
this.valueProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
if ((oldValue == null) && (newValue != null)) {
if (this.getSelectionModel().getSelectedIndex() < 0) {
this.getItems().add(0, newValue);
this.getSelectionModel().clearSelection();
}
} else {
//This throws IndexOutOfBoundsException
this.getSelectionModel().clearSelection();
}
});
}
}
测试类
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class HistoryFieldTest extends Application {
private HistoryField<String> historyField;
@Override
public void start(Stage primaryStage) {
this.historyField = new HistoryField<>();
BorderPane root = new BorderPane();
root.setBottom(historyField);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("History Field Test");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
谢谢!
【问题讨论】:
-
你的问题是什么?您的代码涉及
IndexOutOfBoundsException,但您的问题并未表明您是否遇到了麻烦。究竟什么不起作用? -
@zephyr 这正是我所期望的应用选择然后“重置”
ComboBox即退出编辑模式以便可以再次添加新条目。因为它在if-block 的第一部分起作用。