如何在JavaFX中编辑comboBox?

因此,要编辑JavaFX ComboBox ,请通过将布尔值true作为参数传递来对其调用setEditable()方法。

示例

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
public class ComboBoxEditable extends Application {
   @Override
   public void start(Stage stage) {
      //设置标签
      Label label = new Label("选择所需的课程:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //创建一个组合框
      ComboBox<String> combo = new ComboBox<String>();
      //获取组合框的可观察列表
      ObservableList<String> list = combo.getItems();
      //将项目添加到组合框
      list.add("Java");
      list.add("C++");
      list.add("Python");
      list.add("Big Data");
      list.add("Machine Learning");
     //设置组合框可编辑
      combo.setEditable(true);
      HBox hbox = new HBox(15);
      //在HBox窗格的节点之间设置空间
      hbox.setPadding(new Insets(75, 150, 50, 60));
      hbox.getChildren().addAll(label, combo);
      //创建一个场景对象
      Scene scene = new Scene(new Group(hbox), 595, 280, Color.BEIGE);
      stage.setTitle("Combo Box");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出结果