2017-04-06 77 views
2

我正在尋找javafx JOptionPane等價物,並且我找到了一個很棒的類Dialog。所以在本教程中,導師使用:Dialog<Pair<String,String>>來獲得兩個字符串輸入字段,從這裏我想知道是否可以使用類說:Dialog<Product>。如果可能的話,我應該如何寫這個課程是他們的任何特定模式或情節? 謝謝是否可以在javafx對話框中使用特定的類?

+0

這個想法超出了我的想法,因爲我已經使用JAVAFX和JPA之間的適配器模式 –

回答

2

是的,你可以做到這一點。我的回答是立足於:

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

假設你的產品有兩個字段,可以通過構造函數傳遞:

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

謝謝,我會盡量封裝這個答案以便更好地使用 –

相關問題