2017-05-11 67 views
0

如何在組合框中爲項目添加值,以便用戶可以從現有項目中選擇或選擇「添加元素」項目以添加新項目?從UI向組合框添加值?

private ComboBox<String> comboStructDonnees; 

其次:

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

我不知道我應該創建未來哪個事件,我想文本如果可能的話要添加的元素上輸入。

任何幫助,將不勝感激。

+0

那麼你的意思是你希望用戶能夠添加到可能的選項列表或者你有兩個字段或你想要一個可編輯的組合框? – MadProgrammer

回答

1

您可以將具有「特殊值」的項目(例如空字符串)添加到組合框項目列表的末尾。

使用單元格工廠創建一個單元格,當顯示該值時向用戶顯示用戶友好的消息(例如「添加項目..」)。如果單元格顯示特殊值,則將單元格添加事件過濾器,以顯示用於輸入新值的對話框。

這裏有一個快速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

+0

正是我需要的,謝謝! –