可编辑的ComboBox 中的“小文本字段”称为ComboBox 的editor。这是一个普通的TextField 对象。要访问该对象,您需要使用方法ComboBox#getEditor()。这样您就可以使用TextField 类的方法。如果我理解正确,您要做的就是设置 TextField 的文本。
这是通过comboBox.getEditor().setText(text) 或comboBox.setValue(text) 完成的。这两种方法都将设置 ComboBox 的文本。
但是当您想要获取该文本时会有所不同。 ComboBox#getValue() ComboBox#getEditor()#getText() 不一定返回相同的值。
考虑以下示例:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestComboBox extends Application {
@Override
public void start(Stage stage) {
ComboBox<String> comboBox = new ComboBox<String>();
comboBox.setEditable(true);
comboBox.setValue("Test");
comboBox.getItems().addAll("Test", "Test2", "Test3");
VBox content = new VBox(5);
content.getChildren().add(comboBox);
content.setPadding(new Insets(10));
GridPane valueGrid = new GridPane();
Label cbValue = new Label();
cbValue.textProperty().bind(comboBox.valueProperty());
Label cbText = new Label();
cbText.textProperty().bind(comboBox.getEditor().textProperty());
valueGrid.add(new Label("ComboBox value: "), 0, 0);
valueGrid.add(new Label("ComboBox text: "), 0, 1);
valueGrid.add(cbValue, 1, 0);
valueGrid.add(cbText, 1, 1);
content.getChildren().add(valueGrid);
stage.setScene(new Scene(content));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
如果您通过选择列表中的替代项来更改ComboBox 中的文本,ComboBox#valueProperty() 和ComboBox#getEditor#textProperty() 都会发生变化。但正如您所看到的,如果您在 ComboBox 中输入内容,则只有 textProperty 会发生变化。
因此,当您设置ComboBox 的文本时,请使用您想要的任何方法,但要注意检索该文本时的区别。