Java 类javafx.scene.control.Dialog 实例源码

项目:dwoss    文件:DialogBuilder.java   
/**
 * Creates the javafx Dialog via the producer, shows it and returns the evaluated result as Optional.
 *
 * @param <T>            type of the result
 * @param <P>            result type of the preProducer
 * @param <V>
 * @param dialogProducer the javafx Dialog producer, must not be null and must not return null.
 * @return the result of the evaluation, never null.
 */
public <T, V extends Dialog<T>> Optional<T> eval(Callable<V> dialogProducer) {
    try {
        Objects.requireNonNull(dialogProducer, "The dialogProducer is null, not allowed");

        V dialog = FxSaft.dispatch(dialogProducer);
        Params p = buildParameterBackedUpByDefaults(dialog.getClass());
        if ( isOnceModeAndActiveWithSideeffect(p.key()) ) return Optional.empty();
        dialog.getDialogPane().getScene().setRoot(new BorderPane()); // Remove the DialogPane form the Scene, otherwise an Exception is thrown
        Window window = constructAndShow(SwingCore.wrap(dialog.getDialogPane()), p, Dialog.class); // Constructing the JFrame/JDialog, setting the parameters and makeing it visible
        dialog.getDialogPane().getButtonTypes().stream().map(t -> dialog.getDialogPane().lookupButton(t)).forEach(b -> { // Add Closing behavior on all buttons.
            ((Button)b).setOnAction(e -> {
                L.debug("Close on Dialog called");
                Ui.closeWindowOf(window);
            });
        });
        wait(window);
        return Optional.ofNullable(dialog.getResult());

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:Matcher    文件:UidMenu.java   
private void setup() {
    ProjectConfig config = ProjectConfig.getLast();

    Dialog<ProjectConfig> dialog = new Dialog<>();
    //dialog.initModality(Modality.APPLICATION_MODAL);
    dialog.setResizable(true);
    dialog.setTitle("UID Setup");
    dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

    Node okButton = dialog.getDialogPane().lookupButton(ButtonType.OK);

    UidSetupPane setupPane = new UidSetupPane(config, dialog.getOwner(), okButton);
    dialog.getDialogPane().setContent(setupPane);
    dialog.setResultConverter(button -> button == ButtonType.OK ? config : null);

    dialog.showAndWait().ifPresent(newConfig -> {
        setupPane.updateConfig();

        if (!newConfig.isValid()) return;

        newConfig.saveAsLast();
    });
}
项目:lttng-scope    文件:JfxUtils.java   
/**
     * Utility method to center a Dialog/Alert on the middle of the current
     * screen. Used to workaround a "bug" with the current version of JavaFX (or
     * the SWT/JavaFX embedding?) where alerts always show on the primary
     * screen, not necessarily the current one.
     *
     * @param dialog
     *            The dialog to reposition. It must be already shown, or else
     *            this will do nothing.
     * @param referenceNode
     *            The dialog should be moved to the same screen as this node's
     *            window.
     */
    public static void centerDialogOnScreen(Dialog<?> dialog, Node referenceNode) {
        Window window = referenceNode.getScene().getWindow();
        if (window == null) {
            return;
        }
        Rectangle2D windowRectangle = new Rectangle2D(window.getX(), window.getY(), window.getWidth(), window.getHeight());

        List<Screen> screens = Screen.getScreensForRectangle(windowRectangle);
        Screen screen = screens.stream()
                .findFirst()
                .orElse(Screen.getPrimary());

        Rectangle2D screenBounds = screen.getBounds();
        dialog.setX((screenBounds.getWidth() - dialog.getWidth()) / 2 + screenBounds.getMinX());
//        dialog.setY((screenBounds.getHeight() - dialog.getHeight()) / 2 + screenBounds.getMinY());
    }
项目:JavaFX-EX    文件:SkinManager.java   
public void bind(Dialog<?> dialog) {
  if (map.containsKey(dialog)) {
    return;
  }
  ChangeListener<? super SkinStyle> listener = (ob, o, n) -> {
    dialog.getDialogPane().getStylesheets().remove(o.getURL());
    dialog.getDialogPane().getStylesheets().add(n.getURL());
  };
  if (skin.get() != null) {
    dialog.getDialogPane().getStylesheets().add(skin.get().getURL());
  }
  skin.addListener(listener);
  map.put(dialog, listener);
  dialog.setOnHidden(e -> {
    skin.removeListener(listener);
    map.remove(dialog);
  });
}
项目:shuffleboard    文件:WidgetPaneController.java   
/**
 * Creates the menu for editing the properties of a widget.
 *
 * @param tile the tile to pull properties from
 * @return     the edit property menu
 */
private void showPropertySheet(Tile<?> tile) {
  ExtendedPropertySheet propertySheet = new ExtendedPropertySheet();
  propertySheet.getItems().add(new ExtendedPropertySheet.PropertyItem<>(tile.getContent().titleProperty()));
  Dialog<ButtonType> dialog = new Dialog<>();
  if (tile.getContent() instanceof Widget) {
    ((Widget) tile.getContent()).getProperties().stream()
        .map(ExtendedPropertySheet.PropertyItem::new)
        .forEachOrdered(propertySheet.getItems()::add);
  }

  dialog.setTitle("Edit widget properties");
  dialog.getDialogPane().getStylesheets().setAll(AppPreferences.getInstance().getTheme().getStyleSheets());
  dialog.getDialogPane().setContent(new BorderPane(propertySheet));
  dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CLOSE);

  dialog.showAndWait();
}
项目:HueSense    文件:AboutPresenter.java   
@Override
public void initialize(URL location, ResourceBundle resources) {

    logoImg.setImage(UIUtils.getImage("logo.png"));

    Dialog diag = new Dialog();
    diag.getDialogPane().setContent(borderPane);
    diag.getDialogPane().setBackground(Background.EMPTY);
    diag.setResizable(true);

    UIUtils.setIcon(diag);

    ButtonType closeButton = new ButtonType("Close", ButtonBar.ButtonData.OK_DONE);

    diag.getDialogPane().getButtonTypes().addAll(closeButton);
    diag.setTitle("About HueSense");

    Optional<ButtonType> opt = diag.showAndWait();
    if (opt.isPresent() && opt.get().getButtonData() == ButtonBar.ButtonData.OK_DONE) {
        // nothing
    }

}
项目:vars-annotation    文件:PreferencesDialogController.java   
public void show() {
    paneController.load();
    ResourceBundle i18n = toolBox.getI18nBundle();
    Dialog<ButtonType> dialog = new Dialog<>();
    dialog.setTitle(i18n.getString("prefsdialog.title"));
    dialog.setHeaderText(i18n.getString("prefsdialog.header"));
    GlyphsFactory gf = MaterialIconFactory.get();
    Text settingsIcon = gf.createIcon(MaterialIcon.SETTINGS, "30px");
    dialog.setGraphic(settingsIcon);
    dialog.getDialogPane()
            .getButtonTypes()
            .addAll(ButtonType.OK, ButtonType.CANCEL);
    dialog.getDialogPane()
            .setContent(paneController.getRoot());
    dialog.getDialogPane()
            .getStylesheets()
            .addAll(toolBox.getStylesheets());
    Optional<ButtonType> buttonType = dialog.showAndWait();
    buttonType.ifPresent(bt -> {
        if (bt == ButtonType.OK) {
            paneController.save();
        }
    });
}
项目:vars-annotation    文件:UponBC.java   
protected void init() {

        String tooltip = toolBox.getI18nBundle().getString("buttons.upon");
        MaterialIconFactory iconFactory = MaterialIconFactory.get();
        Text icon = iconFactory.createIcon(MaterialIcon.VERTICAL_ALIGN_BOTTOM, "30px");
        Text icon2 = iconFactory.createIcon(MaterialIcon.VERTICAL_ALIGN_BOTTOM, "30px");
        initializeButton(tooltip, icon);

        ResourceBundle i18n = toolBox.getI18nBundle();
        Dialog<String> dialog = dialogController.getDialog();
        dialog.setTitle(i18n.getString("buttons.upon.dialog.title"));
        dialog.setHeaderText(i18n.getString("buttons.upon.dialog.header"));
        dialog.setContentText(i18n.getString("buttons.upon.dialog.content"));
        dialog.setGraphic(icon2);
        dialog.getDialogPane().getStylesheets().addAll(toolBox.getStylesheets());

    }
项目:vars-annotation    文件:SelectMediaDialogDemo.java   
@Override
public void start(Stage primaryStage) throws Exception {
    MediaService mediaService = DemoConstants.newMediaService();
    AnnotationService annotationService = DemoConstants.newAnnotationService();

    Label label = new Label();
    Button button = new JFXButton("Browse");
    Dialog<Media> dialog = new SelectMediaDialog(annotationService,
            mediaService, uiBundle);
    button.setOnAction(e -> {
        Optional<Media> media = dialog.showAndWait();
        media.ifPresent(m -> label.setText(m.getUri().toString()));
    });

    VBox vBox = new VBox(label, button);
    Scene scene = new Scene(vBox, 400, 200);
    primaryStage.setScene(scene);
    primaryStage.show();

    primaryStage.setOnCloseRequest(e -> {
        Platform.exit();
        System.exit(0);
    });

}
项目:tenhou-visualizer    文件:AppController.java   
public void showAbout(ActionEvent actionEvent) throws URISyntaxException {
    Dialog<Void> dialog = new Dialog<>();
    dialog.setTitle("Tenhou Visualizer について");
    dialog.initOwner(this.root.getScene().getWindow());
    dialog.getDialogPane().getStylesheets().add(this.getClass().getResource(Main.properties.getProperty("css")).toExternalForm());
    dialog.getDialogPane().setGraphic(new ImageView(new Image("/logo.png")));
    dialog.getDialogPane().setHeaderText("TenhouVisualizer v0.3");
    final Hyperlink oss = new Hyperlink("open-source software");
    final URI uri = new URI("https://crazybbb.github.io/tenhou-visualizer/thirdparty");
    oss.setOnAction(e -> {
        try {
            Desktop.getDesktop().browse(uri);
        } catch (IOException e1) {
            throw new UncheckedIOException(e1);
        }
    });
    dialog.getDialogPane().setContent(new TextFlow(new Label("Powered by "), oss));
    dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
    dialog.showAndWait();
}
项目:JavaFX_Tutorial    文件:FXDialogController.java   
/**
 * Constructs and displays dialog based on the FXML at the specified URL
 * 
 * @param url
 *            the location of the FXML file, relative to the
 *            {@code sic.nmsu.javafx} package
 * @param stateInit
 *            a consumer used to configure the controller before FXML injection
 * @return
 */
public static <R, C extends FXDialogController<R>> R show(String url, Consumer<C> stateInit) {
    final Pair<Parent, C> result = FXController.get(url, stateInit);
    final Parent view = result.getValue0();
    final C ctrl = result.getValue1();

    final Dialog<R> dialog = new Dialog<>();
    dialog.titleProperty().bind(ctrl.title);

    final DialogPane dialogPane = dialog.getDialogPane();
    dialogPane.setContent(view);
    dialogPane.getButtonTypes().add(ButtonType.CLOSE);

    final Stage window = (Stage) dialogPane.getScene().getWindow();
    window.getIcons().add(new Image("images/recipe_icon.png"));

    final Node closeButton = dialogPane.lookupButton(ButtonType.CLOSE);
    closeButton.managedProperty().bind(closeButton.visibleProperty());
    closeButton.setVisible(false);

    ctrl.dialog = dialog;
    ctrl.dialog.showAndWait();

    return ctrl.result;
}
项目:standalone-app    文件:DialogHelper.java   
public static void enableClosing(Alert alert) {
    try {
        Field dialogField = Dialog.class.getDeclaredField("dialog");
        dialogField.setAccessible(true);

        Object dialog = dialogField.get(alert);
        Field stageField = dialog.getClass().getDeclaredField("stage");
        stageField.setAccessible(true);

        Stage stage = (Stage) stageField.get(dialog);
        stage.setOnCloseRequest(null);
        stage.addEventFilter(KeyEvent.KEY_PRESSED, keyEvent -> {
            if (keyEvent.getCode() == KeyCode.ESCAPE) {
                ((Button) alert.getDialogPane().lookupButton(ButtonType.OK)).fire();
            }
        });
    } catch (Exception ex) {
        // no point
        ex.printStackTrace();
    }
}
项目:JavaFX-EX    文件:SkinManager.java   
public void bind(Dialog<?> dialog) {
  if (map.containsKey(dialog)) {
    return;
  }
  ChangeListener<? super SkinStyle> listener = (ob, o, n) -> {
    dialog.getDialogPane().getStylesheets().remove(o.getURL());
    dialog.getDialogPane().getStylesheets().add(n.getURL());
  };
  if (skin.get() != null) {
    dialog.getDialogPane().getStylesheets().add(skin.get().getURL());
  }
  skin.addListener(listener);
  map.put(dialog, listener);
  dialog.setOnHidden(e -> {
    skin.removeListener(listener);
    map.remove(dialog);
  });
}
项目:zest-writer    文件:MainApp.java   
private void loadCombinason() {
    scene.addEventFilter(KeyEvent.KEY_PRESSED, t -> {
        String codeStr = t.getCode().toString();
        if(!key.toString().endsWith("_"+codeStr)){
             key.append("_").append(codeStr);
        }
    });
    scene.addEventFilter(KeyEvent.KEY_RELEASED, t -> {
        if(key.length()>0) {
            if("_CONTROL_C_L_E_M".equals(key.toString())){
             // Create the custom dialog.
                Dialog<Void> dialog = new Dialog<>();
                dialog.setTitle(Configuration.getBundle().getString("ui.menu.easteregg"));
                dialog.setHeaderText(null);
                dialog.setContentText(null);
                dialog.setGraphic(new ImageView(this.getClass().getResource("images/goal.gif").toString()));
                dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK);
                dialog.showAndWait();
            }
            key = new StringBuilder();
        }
    });
}
项目:photometric-data-retriever    文件:AppInitializerImpl.java   
private void loadDefaultConfigFile() {
    Task task = new Task() {
        @Override
        protected Object call() throws Exception {
            logger.debug("Started loading default config file");
            try (InputStream inputStream = AppInitializerImpl.class.getResourceAsStream("/pdr_configuration.xml");
                 OutputStream outputStream = new FileOutputStream(configFile)) {
                int read;
                byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                logger.debug("Successfully loaded default configuration file");
            } catch (IOException e) {
                initExceptions.add(new RuntimeException("Failed to copy default configuration to " + configFile.getAbsolutePath(), e));
            }
            return null;
        }
    };
    Dialog dialog = FXMLUtils.getProgressDialog(primaryStage, task);
    executeTask(task);
    dialog.showAndWait();
}
项目:photometric-data-retriever    文件:SearchReportDialogController.java   
@FXML
private void handleExport() {
    File file = FXMLUtils.showSaveFileChooser(resources.getString("choose.output.file"),
            lastSavePath,
            "PDR report",
            stage,
            new FileChooser.ExtensionFilter("Text file (*.txt)", "*.txt"));
    if (file != null) {
        updateLastSavePath(file.getParent());
        Task task = new Task() {
            @Override
            protected Object call() throws Exception {
                try (OutputStream out = new FileOutputStream(file)) {
                    byte[] byteArray = text.get().getBytes();
                    out.write(byteArray, 0, byteArray.length);
                } catch (IOException e) {
                    logger.error(e);
                }
                return null;
            }
        };
        Dialog dialog = FXMLUtils.getProgressDialog(stage, task);
        executor.execute(task);
        dialog.showAndWait();
    }
}
项目:HueSense    文件:AboutPresenter.java   
@Override
public void initialize(URL location, ResourceBundle resources) {

    logoImg.setImage(UIUtils.getImage("logo.png"));

    Dialog diag = new Dialog();
    diag.getDialogPane().setContent(borderPane);
    diag.getDialogPane().setBackground(Background.EMPTY);
    diag.setResizable(true);

    UIUtils.setIcon(diag);

    ButtonType closeButton = new ButtonType("Close", ButtonBar.ButtonData.OK_DONE);

    diag.getDialogPane().getButtonTypes().addAll(closeButton);
    diag.setTitle("About HueSense");

    Optional<ButtonType> opt = diag.showAndWait();
    if (opt.isPresent() && opt.get().getButtonData() == ButtonBar.ButtonData.OK_DONE) {
        // nothing
    }

}
项目:ecasta    文件:WizzardDialogView.java   
/**
 * initiliaze the dialog.
 * 
 * @param stage where to show the dialog.
 * @param testsystem to store data in
 * @return {@link Dialog}
 * @throws IOException when initialization failed
 */
public Dialog<Object> initDialog(Stage stage, Testsystem testsystem) throws IOException {
    if (testsystem != null) {
        edit = true;
        this.testsystem = new Testsystem(testsystem.getId(), testsystem.getName(), testsystem.getUrl());
        this.testsystem.getFeatures().addAll(testsystem.getFeatures());
    } else {
        testsystem = new Testsystem();
        this.testsystem = testsystem;
    }

    this.stage = stage;
    dialog = new Dialog<>();
    dialog.setHeaderText(languageHandler.getMessage(DialogConstants.DIALOG_HEADER));
    dialog.setTitle(languageHandler.getMessage(DialogConstants.DIALOG_TITLE));
    dialog.getDialogPane().setContent(new WizzardDialogFirstStep().init(this.testsystem, this, languageHandler.getDefaultResourceBundle()));
    dialog.setResizable(false);
    dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
    dialog.getDialogPane().lookupButton(ButtonType.CANCEL).setVisible(false);
    dialog.setGraphic(new ImageView(new Image("icons/info_icon-2.png")));
    return dialog;
}
项目:binjr    文件:Dialogs.java   
/**
 * Displays a confirmation dialog box.
 *
 * @param node    a node attached to the stage to be used as the owner of the dialog.
 * @param header  the header message for the dialog.
 * @param content the main message for the dialog.
 * @param icon    the icon for the dialog.
 * @param buttons the {@link ButtonType} that should be displayed on the confirmation dialog.
 * @return the {@link ButtonType} corresponding to user's choice.
 */
public static ButtonType confirmDialog(Node node, String header, String content, Node icon, ButtonType... buttons) {
    Dialog<ButtonType> dlg = new Dialog<>();
    dlg.initOwner(Dialogs.getStage(node));
    setAlwaysOnTop(dlg);
    dlg.setTitle("binjr");
    dlg.getDialogPane().setHeaderText(header);
    dlg.getDialogPane().setContentText(content);
    if (icon == null) {
        icon = new Region();
        icon.getStyleClass().addAll("dialog-icon", "help-icon");
    }
    dlg.getDialogPane().setGraphic(icon);
    if (buttons == null || buttons.length == 0) {
        buttons = new ButtonType[]{ButtonType.YES, ButtonType.NO};
    }
    dlg.getDialogPane().getButtonTypes().addAll(buttons);
    return dlg.showAndWait().orElse(ButtonType.CANCEL);
}
项目:TranslationHelper    文件:JFXDialog.java   
/**
 * Displays a warning dialog with title, message and the options "OK", "Cancel" and "Ignore".
 * The given callbacks are run when the respective buttons are pressed.
 *
 * @param title
 *         The title to use for the dialog
 * @param message
 *         The message of the dialog
 * @param okCallback
 *         Something to run when the user clicks OK
 * @param cancelCallback
 *         Something to run when the user clicks Cancel
 * @param ignoreCallback
 *         Something to run when the user clicks Ignore
 */
public void warn(String title, String message, Runnable okCallback, Runnable cancelCallback, Runnable ignoreCallback) {
    Dialog<ButtonType> d = createBasicDialog(title, message);

    d.getDialogPane().getButtonTypes().addAll(OK, CANCEL, IGNORE);
    Optional<ButtonType> result = d.showAndWait();
    if (result.isPresent()) {
        if (result.get() == OK) {
            okCallback.run();
        } else if (result.get() == CANCEL) {
            cancelCallback.run();
        } else if (result.get() == IGNORE) {
            ignoreCallback.run();
        }
    }
}
项目:JavaFX-Skeleton-DEPRECATED    文件:LoginDialog.java   
private LoginDialog(DialogDescriptor descriptor){
       super(new Dialog<DialogResult>());

       Map<TextFieldDescription, TextField> fields =  createFields(descriptor.getFields());

       Node loginButton = setupButtons(fields);
       setLoginButton(loginButton);

//TODO perform fields validation


//      // Do some validation (using the Java 8 lambda syntax).
//      username.textProperty().addListener((observable, oldValue, newValue) -> {
//          loginButton.setDisable(newValue.trim().isEmpty());
//      });
//
//
//
//      // Request focus on the username field by default.
//      Platform.runLater(() -> username.requestFocus());

    }
项目:standalone-app    文件:DialogHelper.java   
public static void enableClosing(Alert alert) {
    try {
        Field dialogField = Dialog.class.getDeclaredField("dialog");
        dialogField.setAccessible(true);

        Object dialog = dialogField.get(alert);
        Field stageField = dialog.getClass().getDeclaredField("stage");
        stageField.setAccessible(true);

        Stage stage = (Stage) stageField.get(dialog);
        stage.setOnCloseRequest(null);
        stage.addEventFilter(KeyEvent.KEY_PRESSED, keyEvent -> {
            if (keyEvent.getCode() == KeyCode.ESCAPE) {
                ((Button) alert.getDialogPane().lookupButton(ButtonType.OK)).fire();
            }
        });
    } catch (Exception ex) {
        // no point
        ex.printStackTrace();
    }
}
项目:StudyGuide    文件:ChooseCourseDialogPaneCreator.java   
/**
 * Create the dialog for choosing courses.
 *
 * @param courseList the list of courses to show in the dialog (let the user pick from them)
 * @return the controller of the dialog window, enabling to display the dialog and read the selected result
 */
public ChooseCourseController create(List<Course> courseList) {
    FXMLLoader fxmlLoader = this.fxmlLoader.get();
    DialogPane dialogPane = null;
    try (InputStream is = getClass().getResourceAsStream("ChooseCourseDialogPane.fxml")) {
        dialogPane = fxmlLoader.load(is);
    } catch (IOException e) {
        AlertCreator.handleLoadLayoutError(fxmlLoader.getResources(), e);
    }
    ChooseCourseController chooseCourseController = fxmlLoader.getController();
    chooseCourseController.setCourseList(courseList);
    Dialog<ButtonType> dialog = new Dialog<>();
    dialog.setDialogPane(dialogPane);
    chooseCourseController.setDialog(dialog);
    dialog.setTitle("StudyGuide");
    return chooseCourseController;
}
项目:StudyGuide    文件:EnterStringDialogPaneCreator.java   
/**
 * Create the dialog for entering a String.
 *
 * @param prompt the string message to prompt the user with
 * @return the controller of the dialog window, enabling to display the dialog and read the selected result
 */
public EnterStringController create(String prompt) {
    FXMLLoader fxmlLoader = this.fxmlLoader.get();
    DialogPane dialogPane = null;
    try (InputStream is = getClass().getResourceAsStream("EnterStringDialogPane.fxml")) {
        dialogPane = fxmlLoader.load(is);
    } catch (IOException e) {
        AlertCreator.handleLoadLayoutError(fxmlLoader.getResources(), e);
    }
    dialogPane.setHeaderText(prompt);
    EnterStringController enterStringController = fxmlLoader.getController();
    Dialog<ButtonType> dialog = new Dialog<>();
    dialog.initModality(Modality.APPLICATION_MODAL);
    dialog.setDialogPane(dialogPane);
    enterStringController.setDialog(dialog);
    dialog.setTitle("StudyGuide");
    dialog.setOnShown(event -> enterStringController.getTextField().requestFocus());
    return enterStringController;
}
项目:StudyGuide    文件:FindCoursesController.java   
/**
 * Handles search, displaying the found courses for user choice and selecting one of them.
 *
 * @param input the input string (id or name part)
 * @return null if the course wasn't found or the user didn't choose anything
 */
public Course searchAndChooseCourse(String input) {
    List<Course> courses = findCourses(input).collect(Collectors.toList());
    logger.debug("Courses found for input \"{}\": {}", input, Arrays.toString(courses.toArray()));

    if (courses.isEmpty()) {
        AlertCreator.showAlert(Alert.AlertType.INFORMATION,
                String.format(messages.getString("studyPane.cannotFindCourse"), input));
        return null;
    }

    ChooseCourseController controller = chooseCourseDialogPaneCreator.create(courses);
    Dialog<ButtonType> chooseCourseDialog = controller.getDialog();
    Optional<ButtonType> result = chooseCourseDialog.showAndWait();
    if (result.isPresent() && result.get() == ButtonType.APPLY) {
        return controller.getChosenCourse();
    } else {
        return null;
    }
}
项目:SimpleTaskList    文件:AbstractDialogController.java   
/**
 * Initialize a dialog by setting its title, header and content
 * and set window style to "utility dialog".
 *
 * @param dialog The dialog to initialize
 * @param keyTitle Key for dialog title in the translation file
 * @param keyHeader Key for dialog header in the translation file
 * @param keyContent Key for dialog content in the translation file
 * @param windowData The position and size of the parent window
 */
protected static void prepareDialog(final Dialog dialog, final String keyTitle,
        final String keyHeader, final String keyContent, final ParentWindowData windowData) {
    dialog.setTitle(TRANSLATIONS.getString(keyTitle));
    dialog.setHeaderText(TRANSLATIONS.getString(keyHeader));
    dialog.setContentText(TRANSLATIONS.getString(keyContent));
    ((Stage) dialog.getDialogPane().getScene().getWindow()).initStyle(StageStyle.UTILITY);
    dialog.setResizable(false);

    /* Handler to place the dialog in the middle of the main window instead of the middle
     * of the screen; the width oh the dialog is fixed. */
    dialog.setOnShown(new EventHandler<DialogEvent>() {
        public void handle(final DialogEvent event) {
            dialog.setWidth(DIALOG_WIDTH);
            dialog.getDialogPane().setMaxWidth(DIALOG_WIDTH);
            dialog.getDialogPane().setMinWidth(DIALOG_WIDTH);
            dialog.setX(windowData.getX() + (windowData.getWidth() / 2) - (dialog.getWidth() / 2));
            dialog.setY(windowData.getY() + 30);
        }
    });
}
项目:mongofx    文件:UIBuilder.java   
public Optional<String> editDocument(String formattedJson, int cursorPosition) {
  Dialog<String> dialog = new Dialog<>();
  dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
  dialog.setTitle("MongoFX - edit document");
  dialog.setResizable(true);
  dialog.getDialogPane().getStylesheets().add(getClass().getResource("/ui/editor.css").toExternalForm());

  CodeArea codeArea = setupEditorArea(formattedJson, dialog, cursorPosition);

  dialog.setResultConverter(bt -> {
    if (ButtonData.OK_DONE == bt.getButtonData()) {
      return codeArea.getText();
    }
    return null;
  });
  return dialog.showAndWait();
}
项目:mongofx    文件:UIBuilder.java   
private CodeArea setupEditorArea(String formattedJson, Dialog<String> dialog, int cursorPosition) {
  URL url = getClass().getResource("/ui/Editor.fxml");
  final FXMLLoader loader = createLoader(url);
  BorderPane root = load(url, loader);
  EditorController editorController = loader.getController();
  CodeArea codeArea = editorController.getCodeArea();
  codeArea.setPrefSize(500, 400);
  codeArea.replaceText(formattedJson);
  codeArea.getUndoManager().forgetHistory();

  // stackpane is workaround https://github.com/TomasMikula/RichTextFX/issues/196
  dialog.getDialogPane().setContent(new StackPane(root));
  Platform.runLater(() -> {
    codeArea.selectRange(cursorPosition, cursorPosition);
    codeArea.requestFocus();
  });
  return codeArea;
}
项目:iText-GUI    文件:Controller.java   
private void pickStylerToConfigure(final List<Parameterizable> stylers) {
   if (stylers.size() == 1) {
      selectInCombo(stylers.get(0));
      return;
   } else if (stylers.isEmpty()) {
      selectInCombo(null);
      return;
   }
   List<ParameterizableWrapper> pw = new ArrayList<>(stylers.size());
   stylers.stream().forEach((p) -> {
      pw.add(new ParameterizableWrapper(p));
   });
   Dialog<ParameterizableWrapper> dialog = new ChoiceDialog<>(pw.get(0), pw);
   ButtonType bt = new ButtonType("choose", ButtonBar.ButtonData.OK_DONE);
   dialog.getDialogPane().getButtonTypes().clear();
   dialog.getDialogPane().getButtonTypes().add(bt);
   dialog.setTitle("Please choose");
   dialog.setHeaderText(null);
   dialog.setResizable(true);
   dialog.setContentText("choose the styler or condition you want to configure");
   Optional<ParameterizableWrapper> choice = dialog.showAndWait();
   if (choice.isPresent()) {
      selectInCombo(choice.get().p);
   }
}
项目:GRIP    文件:AddSourceButton.java   
/**
 * @param dialog               The dialog to load the camera with.
 * @param cameraSourceSupplier The supplier that will create the camera.
 * @param failureCallback      The handler for when the camera source supplier throws an IO
 *                             Exception.
 */
private void loadCamera(Dialog<ButtonType> dialog, SupplierWithIO<CameraSource>
    cameraSourceSupplier, Consumer<IOException> failureCallback) {
  assert Platform.isFxApplicationThread() : "Should only run in FX thread";
  dialog.showAndWait().filter(Predicate.isEqual(ButtonType.OK)).ifPresent(result -> {
    try {
      // Will try to create the camera with the values from the supplier
      final CameraSource source = cameraSourceSupplier.getWithIO();
      eventBus.post(new SourceAddedEvent(source));
    } catch (IOException e) {
      // This will run it again with the new values retrieved by the supplier
      failureCallback.accept(e);
      loadCamera(dialog, cameraSourceSupplier, failureCallback);
    }
  });
}
项目:GRIP    文件:MainWindowController.java   
/**
 * If there are any steps in the pipeline, give the user a chance to cancel an action or save the
 * current project.
 *
 * @return true If the user has not chosen to
 */
private boolean showConfirmationDialogAndWait() {
  if (!pipeline.getSteps().isEmpty() && project.isSaveDirty()) {
    final ButtonType save = new ButtonType("Save");
    final ButtonType dontSave = ButtonType.NO;
    final ButtonType cancel = ButtonType.CANCEL;

    final Dialog<ButtonType> dialog = new Dialog<>();
    dialog.getDialogPane().getStylesheets().addAll(root.getStylesheets());
    dialog.getDialogPane().setStyle(root.getStyle());
    dialog.setTitle("Save Project?");
    dialog.setHeaderText("Save the current project first?");
    dialog.getDialogPane().getButtonTypes().setAll(save, dontSave, cancel);

    if (!dialog.showAndWait().isPresent()) {
      return false;
    } else if (dialog.getResult().equals(cancel)) {
      return false;
    } else if (dialog.getResult().equals(save)) {
      // If the user chose "Save", automatically show a save dialog and block until the user
      // has had a chance to save the project.
      return saveProject();
    }
  }
  return true;
}
项目:GRIP    文件:MainWindowController.java   
@FXML
protected void deploy() {
  eventBus.post(new WarningEvent(
      "Deploy has been deprecated",
      "The deploy tool has been deprecated and is no longer supported. "
          + "It will be removed in a future release.\n\n"
          + "Instead, use code generation to create a Java, C++, or Python class that handles all"
          + " the OpenCV code and can be easily integrated into a WPILib robot program."));

  ImageView graphic = new ImageView(new Image("/edu/wpi/grip/ui/icons/settings.png"));
  graphic.setFitWidth(DPIUtility.SMALL_ICON_SIZE);
  graphic.setFitHeight(DPIUtility.SMALL_ICON_SIZE);

  deployPane.requestFocus();

  Dialog<ButtonType> dialog = new Dialog<>();
  dialog.setTitle("Deploy");
  dialog.setHeaderText("Deploy");
  dialog.setGraphic(graphic);
  dialog.getDialogPane().getButtonTypes().setAll(ButtonType.CLOSE);
  dialog.getDialogPane().styleProperty().bind(root.styleProperty());
  dialog.getDialogPane().getStylesheets().setAll(root.getStylesheets());
  dialog.getDialogPane().setContent(deployPane);
  dialog.setResizable(true);
  dialog.showAndWait();
}
项目:dwoss    文件:DialogBuilder.java   
/**
 * Creates the javafx Dialog via the producer, supplies the consumer part with the result of the preProducer, shows it and returns the evaluated result as
 * Optional.
 *
 * @param <T>            type of the result
 * @param <P>            result type of the preProducer
 * @param <V>
 * @param preProducer    the preproducer, must not be null
 * @param dialogProducer the javafx Dialog producer, must not be null and must not return null.
 * @return the result of the evaluation, never null.
 */
public <T, P, V extends Dialog<T> & Consumer<P>> Optional<T> eval(Callable<P> preProducer, Callable<V> dialogProducer) {
    try {
        Objects.requireNonNull(dialogProducer, "The dialogProducer is null, not allowed");

        V dialog = FxSaft.dispatch(dialogProducer);
        Params p = buildParameterBackedUpByDefaults(dialog.getClass());
        P preResult = callWithProgress(preProducer);
        p.optionalSupplyId(preResult);
        if ( isOnceModeAndActiveWithSideeffect(p.key()) ) return Optional.empty();
        dialog.accept(preResult); // Calling the preproducer and setting the result in the panel
        dialog.getDialogPane().getScene().setRoot(new BorderPane()); // Remove the DialogPane form the Scene, otherwise an Exception is thrown
        Window window = constructAndShow(SwingCore.wrap(dialog.getDialogPane()), p, Dialog.class); // Constructing the JFrame/JDialog, setting the parameters and makeing it visible
        dialog.getDialogPane().getButtonTypes().stream().map(t -> dialog.getDialogPane().lookupButton(t)).forEach(b -> { // Add Closing behavior on all buttons.
            ((Button)b).setOnAction(e -> {
                L.debug("Close on Dialog called");
                Ui.closeWindowOf(window);
            });
        });
        wait(window);
        return Optional.ofNullable(dialog.getResult());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:systemdesign    文件:Interactions.java   
@Override
public Optional<Color> colorInput(String action, String question, Color _default) {
    Dialog<Color> dialog = new Dialog<>();
    dialog.setTitle(action);
    dialog.setHeaderText(question);
    ColorPicker picker = new ColorPicker(_default);
    Button randomiser = new Button("Mix");
    randomiser.setOnAction(e -> {
        Color current = picker.getValue();
        Color shifted = Item.shiftColor(current);
        picker.setValue(shifted);
    });
    HBox box = new HBox();
    box.getChildren().addAll(picker, randomiser);
    dialog.getDialogPane().setContent(box);

    dialog.getDialogPane().getButtonTypes().addAll(
            ButtonType.OK, ButtonType.CANCEL);

    dialog.setResultConverter(buttonType -> {
        if (buttonType.equals(ButtonType.OK)) {
            return picker.getValue();
        } else {
            return null;
        }
    });
    return dialog.showAndWait();
}
项目:Matcher    文件:FileMenu.java   
private void newProject() {
    ProjectConfig config = ProjectConfig.getLast();

    Dialog<ProjectConfig> dialog = new Dialog<>();
    //dialog.initModality(Modality.APPLICATION_MODAL);
    dialog.setResizable(true);
    dialog.setTitle("Project configuration");
    dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

    Node okButton = dialog.getDialogPane().lookupButton(ButtonType.OK);

    dialog.getDialogPane().setContent(new NewProjectPane(config, dialog.getOwner(), okButton));
    dialog.setResultConverter(button -> button == ButtonType.OK ? config : null);

    dialog.showAndWait().ifPresent(newConfig -> {
        if (!newConfig.isValid()) return;

        newConfig.saveAsLast();

        gui.getMatcher().reset();
        gui.onProjectChange();

        gui.runProgressTask("Initializing files...",
                progressReceiver -> gui.getMatcher().init(newConfig, progressReceiver),
                () -> gui.onProjectChange(),
                Throwable::printStackTrace);
    });
}
项目:Matcher    文件:FileMenu.java   
private void loadProject() {
    Path file = Gui.requestFile("Select matches file", gui.getScene().getWindow(), getMatchesLoadExtensionFilters(), true);
    if (file == null) return;

    List<Path> paths = new ArrayList<>();

    Dialog<List<Path>> dialog = new Dialog<>();
    //dialog.initModality(Modality.APPLICATION_MODAL);
    dialog.setResizable(true);
    dialog.setTitle("Project paths");
    dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

    Node okButton = dialog.getDialogPane().lookupButton(ButtonType.OK);

    dialog.getDialogPane().setContent(new LoadProjectPane(paths, dialog.getOwner(), okButton));
    dialog.setResultConverter(button -> button == ButtonType.OK ? paths : null);

    dialog.showAndWait().ifPresent(newConfig -> {
        if (paths.isEmpty()) return;

        gui.getMatcher().reset();
        gui.onProjectChange();

        gui.runProgressTask("Initializing files...",
                progressReceiver -> gui.getMatcher().readMatches(file, paths, progressReceiver),
                () -> gui.onProjectChange(),
                Throwable::printStackTrace);
    });
}
项目:lttng-scope    文件:ModelConfigButton.java   
/**
 * Constructor
 *
 * @param widget
 *            The time graph widget to which this toolbar button is
 *            associated.
 */
public ModelConfigButton(TimeGraphWidget widget) {
    Image icon = JfxImageFactory.instance().getImageFromResource(LEGEND_ICON_PATH);
    setGraphic(new ImageView(icon));
    setTooltip(new Tooltip(Messages.modelConfigButtonName));

    setOnAction(e -> {
        Dialog<?> dialog = new ModelConfigDialog(widget);
        dialog.show();
        JfxUtils.centerDialogOnScreen(dialog, ModelConfigButton.this);
    });
}
项目:lttng-scope    文件:DebugOptionsButton.java   
/**
 * Constructor
 *
 * @param widget
 *            The time graph widget to which this toolbar button is
 *            associated.
 */
public DebugOptionsButton(TimeGraphWidget widget) {
    Image icon = JfxImageFactory.instance().getImageFromResource(CONFIG_ICON_PATH);
    setGraphic(new ImageView(icon));
    setTooltip(new Tooltip(Messages.debugOptionsDialogName));

    fOpts = widget.getDebugOptions();

    setOnAction(e -> {
        Dialog<Void> dialog = new DebugOptionsDialog(this);
        dialog.show();
        JfxUtils.centerDialogOnScreen(dialog, DebugOptionsButton.this);
    });
}
项目:qiniu    文件:Dialogs.java   
public Dialog<String[]> getDialog(ButtonType ok) {
    Dialog<String[]> dialog = new Dialog<String[]>();
    dialog.setTitle(Values.MAIN_TITLE);
    dialog.setHeaderText(null);

    dialog.initModality(Modality.APPLICATION_MODAL);

    // 自定义确认和取消按钮
    ButtonType cancel = new ButtonType(Values.CANCEL, ButtonData.CANCEL_CLOSE);
    dialog.getDialogPane().getButtonTypes().addAll(ok, cancel);
    return dialog;
}
项目:javaGMR    文件:GamepaneController.java   
@FXML
protected void uploadGame() {
    if (!new File(JGMRConfig.getInstance().getPath() + "/.jgmrlock.lock").exists()) {
        FileChooser directoryChooser = new FileChooser();
        if (JGMRConfig.getInstance().getPath() != null) {
            directoryChooser.setInitialDirectory(new File(JGMRConfig.getInstance().getPath()));
        }
        Stage stage = new Stage();
        File fileResult = directoryChooser.showOpenDialog(stage);
        if (fileResult != null) {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle("Upload to " + game.getName());
            alert.setHeaderText("Upload to " + game.getName());
            alert.setContentText("Are you sure you wish to upload " + fileResult.getName() + " to the game " + game.getName());
            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == ButtonType.OK) {
                uploadGame(fileResult);
            }
        }
    } else {
        Dialog dg = new Dialog();
        dg.setContentText("An upload or download is already in progress, please wait for the previous operation to finish.");
        dg.setTitle("Download or Upload already in progress.");
        dg.getDialogPane().getButtonTypes().add(new ButtonType("Ok", ButtonBar.ButtonData.OK_DONE));
        Platform.runLater(() -> {
            dg.showAndWait();
        });
    }
}