I work on desktop application based on JDK 8 and JavaFX.
I created custom dialog class with 2 buttons(finish and cancel). My goal is to return the list of strings added in dialog (after clicking finish button, dialog returns list. Cancel makes return empty list).
I have problem, beacause function showAndWait return type of button which I clicked (‘ButtonType.FINISH’ or ‘ButtonType.CANCEL’). My goal is to override default action on finish and close button and I want to return list instead of return button type.
It’s always possible to create custom buttons, however, it would be better to use those already provided by JavaFX.
In response, you can use any of the JVM languages (Java/Kotlin/Scala).
Code:
class MyDialog : Dialog<MutableList<String>>() { val listToReturn: MutableList<String> = mutableListOf() init { val dialogPane: DialogPane = this.dialogPane dialogPane.buttonTypes.addAll(ButtonType.FINISH, ButtonType.CANCEL) } }
val myDialog: MyDialog = MyDialog() // here I got ButtonType ('ButtonType.FINISH' or 'ButtonType.CANCEL'), not list of string myDialog.showAndWait().ifPresent { list -> println(list) }
Advertisement
Answer
You need to use a result converter
public class MyDialog extends Dialog<List<String>> { ArrayList<String> returnList = new ArrayList<>(); public MyDialog() { returnList.add("test 1"); returnList.add("test 2"); this.getDialogPane().getButtonTypes().addAll(ButtonType.FINISH, ButtonType.CANCEL); setResultConverter(dialogButton -> { if (dialogButton == ButtonType.FINISH) { return returnList; } return new ArrayList<>(); }); } }
and for the application side
public class main extends Application { public static void main (String [] args) { launch(); } @Override public void start(Stage primaryStage) { MyDialog myDialog = new MyDialog(); myDialog.showAndWait().ifPresent(System.out::println); } }