2016-07-22 2 views
0

사용자가 항목을 선택한 후에 해당 항목의 비용이 콤보 상자 아래에 표시되는 JavaFX에 여러 콤보 상자를 추가하고 싶습니다. 또한 선택한 모든 항목의 총 비용이 하단에 표시됩니다. 내가 선택 한 항목의 비용을 표시하지만 여러 사람을 만드는 방법을 알아낼 수 없습니다 및항목을 선택하고 나면 아래에 비용이 표시되는 JavaFX에 여러 콤보 상자를 추가하려면 어떻게해야합니까?

import javafx.application.Application; 
import javafx.geometry.Insets; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.ComboBox; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.VBox; 
import javafx.scene.text.Text; 
import javafx.stage.Stage; 
import javafx.util.StringConverter; 
import javafx.collections.FXCollections; 

public class Animals extends Application { 

    Stage window; 
    Scene scene; 
    Button button; 
    ComboBox<Animal> comboBox = new ComboBox<Animal>(); 
    Text textNamePrice = new Text(); 

    static public TextField[] tfLetters = new TextField[37]; 

    public static void main(String[] args) { 
     launch(args); 
    } 

    @Override 
    public void start(Stage primaryStage) throws Exception { 
     window = primaryStage; 
     window.setTitle("ComboBox "); 
     button = new Button("Submit"); 

     comboBox = new ComboBox<Animal>(); 

     comboBox.setConverter(new StringConverter<Animal>() { 
      @Override 
      public String toString(Animal object) { 
       return object.getName(); 
      } 

      @Override 
      public Animal fromString(String string) { 
       return null; 
      } 
     }); 

     comboBox.setItems(FXCollections.observableArrayList(new Animal("Dog", 30.12), new Animal("Cat", 23.23), 
       new Animal("Bird", 15.0))); 

     comboBox.valueProperty().addListener((obs, oldVal, newVal) -> { 
      String selectionText = "Price of the " + newVal.getName() + " is : " + newVal.getPrice(); 

      System.out.println(selectionText); 
      textNamePrice.setText(selectionText); 
     }); 

     VBox layout = new VBox(10); 
     layout.setPadding(new Insets(60, 60, 60, 60)); 
     layout.getChildren().addAll(comboBox, textNamePrice, button); 

     scene = new Scene(layout, 500, 350); 
     window.setScene(scene); 
     window.show(); 
    } 

    public class Animal { 
     private String name; 
     private Double price; 

     public Double getPrice() { 
      return price; 
     } 

     public String getName() { 
      return name; 
     } 

     public Animal(String name, Double price) { 
      this.name = name; 
      this.price = price; 
     } 
    } 
} 

답변

0

그것은 사용자 정의를 사용하는 probabls 가장 쉬운 방법을 선택한 모든 비용을 표시 한 콤보 상자를 만드는 방법을 알고 ComboBox + 가격을 표시하는 Node 유형 AnimalChooser 이 방법은 하나의 선택 + 가격 표시 기능을 한 곳에서 처리 할 수 ​​있습니다. 또한 선택 기준에 따라 price 속성을 제공하여 애플리케이션 클래스에서 이들을 합산 할 수 있습니다.

다음 예제에서는 모두 을 VBox에 넣고 자식 목록에 수신기를 추가하여 자식 목록에 추가/제거하고 수정해야 할 경우 해당 자식 목록을 동적으로 추가/제거 할 수 있습니다 AnimalChooserVBox에 /로부터 가져오고 올바르게 업데이트 된 합계를 얻습니다.

public class Animal { 

    private final String name; 
    // primitive type should be prefered here 
    private final double price; 

    public double getPrice() { 
     return price; 
    } 

    public String getName() { 
     return name; 
    } 

    public Animal(String name, double price) { 
     this.name = name; 
     this.price = price; 
    } 
} 
public class AnimalChooser extends VBox { 

    private final ComboBox<Animal> animalCombo; 
    private final ReadOnlyDoubleWrapper price; 
    private final Text text; 

    public AnimalChooser(ObservableList<Animal> items) { 
     setSpacing(5); 
     animalCombo = new ComboBox<>(items); 

     // converter for using a custom string representation of Animal in the 
     // combobox 
     animalCombo.setConverter(new StringConverter<Animal>() { 

      @Override 
      public String toString(Animal object) { 
       return object == null ? "" : object.getName(); 
      } 

      @Override 
      public Animal fromString(String string) { 
       if (string == null || string.isEmpty()) { 
        return null; 
       } else { 

        // find suitable animal from list 
        Animal animal = null; 

        for (Animal item : items) { 
         if (string.equals(item.getName())) { 
          animal = item; 
          break; 
         } 
        } 

        return animal; 
       } 
      } 

     }); 

     text = new Text(); 
     price = new ReadOnlyDoubleWrapper(); 

     getChildren().addAll(animalCombo, text); 

     // bind price value to price property 
     price.bind(Bindings.createDoubleBinding(new Callable<Double>() { 

      @Override 
      public Double call() throws Exception { 
       Animal animal = animalCombo.getValue(); 
       return animal == null ? 0d : animal.getPrice(); 
      } 
     }, animalCombo.valueProperty())); 

     // bind text to content of Text node 
     text.textProperty().bind(Bindings.when(animalCombo.valueProperty().isNull()).then("").otherwise(price.asString("%.2f $"))); 
    } 

    public final double getPrice() { 
     return this.price.get(); 
    } 

    public final ReadOnlyDoubleProperty priceProperty() { 
     return this.price.getReadOnlyProperty(); 
    } 

} 
@Override 
public void start(Stage primaryStage) { 

    VBox animalChoosers = new VBox(20); 

    ObservableList<Animal> animals = FXCollections.observableArrayList(
      new Animal("cat", 1000.99), 
      new Animal("dog", 20.50), 
      new Animal("goldfish", 15.22) 
    ); 

    final DoubleProperty total = new SimpleDoubleProperty(); 

    InvalidationListener listener = new InvalidationListener() { 

     @Override 
     public void invalidated(Observable observable) { 
      double sum = 0d; 
      for (Node n : animalChoosers.getChildren()) { 
       AnimalChooser chooser = (AnimalChooser) n; 
       sum += chooser.getPrice(); 
      } 

      total.set(sum); 
     } 
    }; 

    // just in case you want to add AnimalChooser s dynamially to animalChoosers 
    animalChoosers.getChildren().addListener(new ListChangeListener<Node>() { 

     @Override 
     public void onChanged(ListChangeListener.Change<? extends Node> c) { 
      while (c.next()) { 
       // add remove listeners updating the total 
       for (Node n : c.getRemoved()) { 
        AnimalChooser chooser = (AnimalChooser) n; 
        chooser.priceProperty().removeListener(listener); 
       } 
       for (Node n : c.getAddedSubList()) { 
        AnimalChooser chooser = (AnimalChooser) n; 
        chooser.priceProperty().addListener(listener); 
       } 
      } 

      listener.invalidated(null); 
     } 

    }); 

    for (int i = 0; i < 10; i++) { 
     animalChoosers.getChildren().add(new AnimalChooser(animals)); 
    } 

    BorderPane root = new BorderPane(animalChoosers); 
    Text totalText = new Text(); 
    totalText.textProperty().bind(total.asString("total: %.2f $")); 

    root.setBottom(totalText); 
    BorderPane.setMargin(totalText, new Insets(20)); 

    Scene scene = new Scene(root); 

    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 
관련 문제