2017-04-06 18 views
2

私はjavafx JOptionPane相当物を探していました。私は素晴らしいクラスのDialogを見つけました。だから、チュートリアルでは、チューターはDialog<Pair<String,String>>を使用して2つの文字列入力フィールドを取得しました。ここからは、クラスを使用することが可能ですか?Dialog<Product>。可能であれば、どのように私はこのクラスを書く必要がありますか? ありがとうございますjavafxダイアログで特定のクラスを使用することはできますか?

+0

https://examples.javacodegeeks.com/desktop-java/javafx/dialog-javafx/javafx-dialog-example/

は、あなたの製品は、コンストラクタを介して渡すことができる2つのフィールドがあり仮定すると、この考えは私がJAVAFXとJPAの間ですでにアダプターパターンを使用しているので私の心を横切った –

答えて

2

はい、できます。私の答えは上基づかれる:

String name; 
float price; 

あなたは、このような方法であなたのダイアログを作成することができます:

Dialog<Product> dialog = new Dialog<>(); 
dialog.setTitle("Product Dialog"); 
dialog.setResizable(true); 

Label nameLabel = new Label("Name: "); 
Label priceLabel = new Label("Price: "); 
TextField nameField = new TextField(); 
TextField priceField = new TextField(); 

GridPane grid = new GridPane(); 
grid.add(nameLabel, 1, 1); 
grid.add(nameField, 2, 1); 
grid.add(priceLabel, 1, 2); 
grid.add(priceField, 2, 2); 
dialog.getDialogPane().setContent(grid); 

ButtonType saveButton = new ButtonType("Save", ButtonData.OK_DONE); 
dialog.getDialogPane().getButtonTypes().add(saveButton); 

dialog.setResultConverter(new Callback<ButtonType, Product>() { 
    @Override 
    public Product call(ButtonType button) { 
     if (button == saveButton) { 
      String name = nameField.getText(); 
      Float price; 
      try { 
       price = Float.parseFloat(priceField.getText()); 
      } catch (NumberFormatException e) { 
       // Add some log or inform user about wrong price 
       return null; 
      } 

      return new Product(name, price); 
     } 

     return null; 
    } 
}); 

Optional<Product> result = dialog.showAndWait(); 

if (result.isPresent()) { 
    Product product = result.get(); 
    // Do something with product 
} 
+1

リンク専用の答えは推奨されません。なぜなら、外部URL goeあなたの答えは将来の読者には役に立たない。あなたの答えに説明を加えてください。 – VGR

+0

良い点、ありがとう!私は自分の答えを更新しました – LLL

+0

ありがとう、私はこの答えをより良い将来の使用のためにカプセル化しようとします –

関連する問題