2017-05-11 5 views
0

コンボボックス内のアイテムに値を追加する方法を教えてください。ユーザーは既存のアイテムまたはクリーク「アイテムを追加」アイテムを選択して新しいアイテムを追加できますか?私は可能な場合は追加された要素に入力するテキストにしたい、私は私が次に作成すべきイベントがわからないUIからコンボボックスに値を追加しますか?

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

private ComboBox<String> comboStructDonnees; 

が続きます。

ご協力いただければ幸いです。

+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

まさに私が必要なもの、感謝! –

関連する問題