类javafx.scene.control.Alert源码实例Demo

下面列出了怎么用javafx.scene.control.Alert的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: pcgen   文件: RadioChooserDialog.java
private void onOK(final ActionEvent ignored)
{
	Toggle selectedToggle = toggleGroup.getSelectedToggle();
	Logging.debugPrint("selected toggle is " + selectedToggle);
	if (selectedToggle != null)
	{
		Integer whichItemId = (Integer)selectedToggle.getUserData();
		InfoFacade selectedItem = chooser.getAvailableList().getElementAt(whichItemId);
		chooser.addSelected(selectedItem);
	}
	if (chooser.isRequireCompleteSelection() && (chooser.getRemainingSelections().get() > 0))
	{
		Dialog<ButtonType> alert = new Alert(Alert.AlertType.INFORMATION);
		alert.setTitle(chooser.getName());
		alert.setContentText(LanguageBundle.getFormattedString("in_chooserRequireComplete",
				chooser.getRemainingSelections().get()));
		alert.showAndWait();
		return;
	}
	chooser.commit();
	committed = true;
	this.dispose();
}
 
源代码2 项目: markdown-writer-fx   文件: FileEditorTabPane.java
boolean canCloseEditor(FileEditor fileEditor) {
	if (!fileEditor.isModified())
		return true;

	Alert alert = mainWindow.createAlert(AlertType.CONFIRMATION,
		Messages.get("FileEditorTabPane.closeAlert.title"),
		Messages.get("FileEditorTabPane.closeAlert.message"), fileEditor.getTab().getText());
	alert.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);

	// register first characters of Yes and No buttons as keys to close the alert
	for (ButtonType buttonType : Arrays.asList(ButtonType.YES, ButtonType.NO)) {
		Nodes.addInputMap(alert.getDialogPane(),
			consume(keyPressed(KeyCode.getKeyCode(buttonType.getText().substring(0, 1).toUpperCase())), e -> {
				if (!e.isConsumed()) {
					alert.setResult(buttonType);
					alert.close();
				}
			}));
	}

	ButtonType result = alert.showAndWait().get();
	if (result != ButtonType.YES)
		return (result == ButtonType.NO);

	return saveEditor(fileEditor);
}
 
源代码3 项目: pikatimer   文件: FXMLEventController.java
public void removeTimingLocation(ActionEvent fxevent){
    
    final TimingLocation tl = timingLocListView.getSelectionModel().getSelectedItem();
    
    // If the location is referenced by a split, 
    // toss up a warning and leave it alone
    final StringProperty splitsUsing = new SimpleStringProperty();
    raceDAO.listRaces().forEach(r -> {
        r.getSplits().forEach(s -> {
            if (s.getTimingLocation().equals(tl)) splitsUsing.set(splitsUsing.getValueSafe() + r.getRaceName() + " " + s.getSplitName() + "\n");
        });
    });
    
    if (splitsUsing.isEmpty().get()) {
        timingLocationDAO.removeTimingLocation(tl);;
        timingLocAddButton.requestFocus();
        timingLocAddButton.setDefaultButton(true);
    } else {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Unable to Remove Timing Location");
        alert.setHeaderText("Unable to remove the " + tl.getLocationName() + " timing location.");
        alert.setContentText("The timing location is in use by the following splits:\n" + splitsUsing.getValueSafe());

        alert.showAndWait();
    }
}
 
源代码4 项目: pmd-designer   文件: SimplePopups.java
public static void showAboutPopup(DesignerRoot root) {
    Alert licenseAlert = new Alert(AlertType.INFORMATION);
    licenseAlert.setWidth(500);
    licenseAlert.setHeaderText("About");

    ScrollPane scroll = new ScrollPane();
    TextArea textArea = new TextArea();

    String sb =
        "PMD core version:\t\t\t" + PMDVersion.VERSION + "\n"
            + "Designer version:\t\t\t" + Designer.getCurrentVersion()
            + " (supports PMD core " + Designer.getPmdCoreMinVersion() + ")\n"
            + "Designer settings dir:\t\t"
            + root.getService(DesignerRoot.DISK_MANAGER).getSettingsDirectory() + "\n"
            + "Available languages:\t\t"
            + AuxLanguageRegistry.getSupportedLanguages().map(Language::getTerseName).collect(Collectors.toList())
            + "\n";

    textArea.setText(sb);
    scroll.setContent(textArea);

    licenseAlert.getDialogPane().setContent(scroll);
    licenseAlert.showAndWait();
}
 
源代码5 项目: uip-pc2   文件: Resumen.java
public void transferir(ActionEvent actionEvent) {
    Stage stage = (Stage) movimientos.getScene().getWindow();
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Transferencia.fxml"));
    Parent root = null;
    try {
        root = fxmlLoader.load();
    } catch (Exception e) {
        Alert alerta = new Alert(Alert.AlertType.ERROR);
        alerta.setTitle("Error de Aplicación");
        alerta.setContentText("Llama al lapecillo de sistemas.");
        alerta.showAndWait();
        Platform.exit();
    }
    FadeTransition ft = new FadeTransition(Duration.millis(1500), root);
    ft.setFromValue(0.0);
    ft.setToValue(1.0);
    ft.play();
    Transferencia controller = fxmlLoader.<Transferencia>getController();
    controller.cargar_datos(cuenta.getText()); // ¯\_(ツ)_/¯ cuenta viene de la linea 27
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}
 
源代码6 项目: uip-pc2   文件: Resumen.java
public void ver(ActionEvent actionEvent) {
    Stage stage = (Stage) movimientos.getScene().getWindow();
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Movimientos.fxml"));
    Parent root = null;
    try {
        root = fxmlLoader.load();
    } catch (Exception e) {
        Alert alerta = new Alert(Alert.AlertType.ERROR);
        alerta.setTitle("Error de Aplicación");
        alerta.setContentText("Llama al lapecillo de sistemas.");
        alerta.showAndWait();
        Platform.exit();
    }
    FadeTransition ft = new FadeTransition(Duration.millis(1500), root);
    ft.setFromValue(0.0);
    ft.setToValue(1.0);
    ft.play();
    Movimientos controller = fxmlLoader.<Movimientos>getController();
    controller.cargar_movimientos(cuenta.getText());
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}
 
源代码7 项目: MyBox   文件: SettingsController.java
@FXML
protected void clearFileHistories(ActionEvent event
) {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle(getBaseTitle());
    alert.setContentText(AppVariables.message("SureClear"));
    alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
    ButtonType buttonSure = new ButtonType(AppVariables.message("Sure"));
    ButtonType buttonCancel = new ButtonType(AppVariables.message("Cancel"));
    alert.getButtonTypes().setAll(buttonSure, buttonCancel);
    Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
    stage.setAlwaysOnTop(true);
    stage.toFront();

    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() != buttonSure) {
        return;
    }
    new TableVisitHistory().clear();
    popSuccessful();
}
 
源代码8 项目: pikatimer   文件: FXMLEventController.java
public void resetRaces(ActionEvent fxevent){
    // prompt 
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Confirm Resetting All Races");
    alert.setContentText("This action cannot be undone.");
    alert.setHeaderText("This will delete all configured races!");
    //Label alertContent = new Label("This will reset the timing locations to default values.\nAll splits will be reassigned to one of the default locations.");
    //alertContent.setWrapText(true); 
    //alert.getDialogPane().setContent(alertContent);
    
    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK){
        raceDAO.clearAll();
    } else {
        // ... user chose CANCEL or closed the dialog
    }
    
    raceAddButton.requestFocus();
    raceAddButton.setDefaultButton(true);
}
 
源代码9 项目: phoebus   文件: ScanEditor.java
@Override
public void execute(UndoableAction action)
{
    final ScanInfoModel infos = scan_info_model.get();
    if (infos != null)
    {
        // Warn that changes to the running scan are limited
        final Alert dlg = new Alert(AlertType.CONFIRMATION);
        dlg.setHeaderText("");
        dlg.setContentText(Messages.scan_active_prompt);
        dlg.setResizable(true);
        dlg.getDialogPane().setPrefSize(600, 300);
        DialogHelper.positionDialog(dlg, scan_tree, -100, -100);
        if (dlg.showAndWait().get() != ButtonType.OK)
            return;

        // Only property change is possible while running.
        // Adding/removing commands detaches from the running scan.
        if (! (action instanceof ChangeProperty))
            detachFromScan();
    }
    super.execute(action);
}
 
public static boolean infoBox(String infoMessage, String headerText, String title){
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setContentText(infoMessage);
    alert.setTitle(title);
    alert.setHeaderText(headerText);
    alert.getButtonTypes();
    
    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK){
        // ... user chose OK button
     return true;
    } else {
    // ... user chose CANCEL or closed the dialog
    return false;
    }
    
}
 
源代码11 项目: ShootOFF   文件: Main.java
/**
 * If we could not acquire writable resources for Webstart, see if we have
 * enough to run anyway.
 */
private void tryRunningShootOFF() {
	if (!new File(System.getProperty("shootoff.home") + File.separator + "shootoff.properties").exists()) {
		final Alert resourcesAlert = new Alert(AlertType.ERROR);
		resourcesAlert.setTitle("Missing Resources");
		resourcesAlert.setHeaderText("Missing Required Resources!");
		resourcesAlert.setResizable(true);
		resourcesAlert.setContentText("ShootOFF could not acquire the necessary resources to run. Please ensure "
				+ "you have a connection to the Internet and can connect to http://shootoffapp.com and try again.\n\n"
				+ "If you cannot get the browser-launched version of ShootOFF to work, use the standlone version from "
				+ "the website.");
		resourcesAlert.showAndWait();
	} else {
		runShootOFF();
	}
}
 
public static boolean infoBox(String infoMessage, String headerText, String title){
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setContentText(infoMessage);
    alert.setTitle(title);
    alert.setHeaderText(headerText);
    alert.getButtonTypes();
    
    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK){
        // ... user chose OK button
     return true;
    } else {
    // ... user chose CANCEL or closed the dialog
    return false;
    }
    
}
 
源代码13 项目: MythRedisClient   文件: ZsetAction.java
/**
 * 修改值.
 *
 * @param key          数据库中的键
 * @param nowSelectRow 当前选择的值
 * @param selected     是否选择值
 */
@Override
public void setValueByIndex(String key, int nowSelectRow, boolean selected) {
    if (selected) {
        ShowPanel showPanel = new ShowPanel();
        boolean ok = showPanel.showValuePanel(true);
        if (ok) {
            String childKey = dataTable.getSelectionModel().getSelectedItem().getKey();
            String value = showPanel.getValueText();
            double score = Double.parseDouble(value);
            redisZset.save(key, score, childKey);
        }
    } else {
        Alert alert = MyAlert.getInstance(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setContentText("请选择一个键");
        alert.showAndWait();
    }
}
 
源代码14 项目: zest-writer   文件: ImageInputDialog.java
private void selectAndUploadImage() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setInitialDirectory(MainApp.getDefaultHome());
    File selectedFile = fileChooser.showOpenDialog(null);
    if (selectedFile != null) {
        UploadImageService uploadImageTask = new UploadImageService(content, selectedFile.getAbsoluteFile());
        uploadImageTask.setOnFailed( t -> {
            Alert alert = new CustomAlert(AlertType.ERROR);
            alert.setTitle(Configuration.getBundle().getString("ui.dialog.upload.img.failed.title"));
            alert.setHeaderText(Configuration.getBundle().getString("ui.dialog.upload.img.failed.header"));
            alert.setContentText(Configuration.getBundle().getString("ui.dialog.upload.img.failed.text"));
            alert.showAndWait();
        });
        uploadImageTask.setOnSucceeded(t -> link.setText(uploadImageTask.getValue()));
        uploadImageTask.start();
    }
}
 
/**
 * Validate input
 *
 * @return
 */
private boolean validInput() {
    TrexAlertBuilder errorBuilder = TrexAlertBuilder.build().setType(Alert.AlertType.ERROR);
    if (Util.isNullOrEmpty(nameTF.getText())) {
        errorBuilder.setContent("Please fill the empty fields");
        errorBuilder.getAlert().showAndWait();
        return false;
    } else if (profileList != null && !profileWindow) {
        for (Profile p : profileList) {
            if (p.getName().equals(nameTF.getText())) {
                errorBuilder.setContent("Stream name already exists, please select a different Stream name");
                errorBuilder.getAlert().showAndWait();
                return false;
            }
        }
    }
    dataAvailabe = true;
    return true;
}
 
源代码16 项目: latexdraw   文件: NewDrawingTest.java
@Override
protected void commonCanDoFixture() {
	final SystemUtils utils = Mockito.mock(SystemUtils.class);
	Mockito.when(utils.getPathTemplatesDirUser()).thenReturn("");
	SystemUtils.setSingleton(utils);
	ui = Mockito.mock(JfxUI.class);
	statusWidget = Mockito.mock(Label.class);
	progressBar = Mockito.mock(ProgressBar.class);
	mainstage = Mockito.mock(Stage.class);
	file = Mockito.mock(File.class);
	modifiedAlert = Mockito.mock(Alert.class);
	openSaveManager = Mockito.mock(OpenSaver.class);
	fileChooser = Mockito.mock(FileChooser.class);
	currentFolder = Optional.empty();

	cmd = new NewDrawing(file, openSaveManager, progressBar, statusWidget, ui, fileChooser, currentFolder, mainstage, modifiedAlert);
}
 
源代码17 项目: blobsaver   文件: Background.java
static void stopBackground(boolean showAlert) {
    inBackground = false;
    executor.shutdownNow();
    if (SwingUtilities.isEventDispatchThread()) {
        SystemTray.getSystemTray().remove(trayIcon);
    } else {
        SwingUtilities.invokeLater(() -> SystemTray.getSystemTray().remove(trayIcon));
    }
    if (showAlert) {
        Utils.runSafe(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION,
                    "The background process has been cancelled",
                    ButtonType.OK);
            alert.showAndWait();
        });
    }
    System.out.println("Stopped background");
}
 
/**
 * Adds the next set of results to the list view.
 */
@FXML
private void getMoreResults() {
  if (portalQueryResultSet.getNextQueryParameters() != null) {
    // find matching portal items
    ListenableFuture<PortalQueryResultSet<PortalItem>> results = portal.findItemsAsync(portalQueryResultSet.getNextQueryParameters());
    results.addDoneListener(() -> {
      try {
        // replace the result set with the current set of results
        portalQueryResultSet = results.get();
        List<PortalItem> portalItems = portalQueryResultSet.getResults();

        // add set of results to list view
        resultsList.getItems().addAll(portalItems);
      } catch (Exception e) {
        e.printStackTrace();
      }
    });
  } else {
    showMessage("End of results", "There are no more results matching this query", Alert.AlertType.INFORMATION);
    moreButton.setDisable(true);
  }
}
 
@FXML
public void showEmployeesHelper(ActionEvent evt) {
	
	Button btn = (Button)evt.getSource();
	
	Point2D point = btn.localToScreen(0.0d + btn.getWidth(), 0.0d - btn.getHeight());
	
	try {
		
		Popup employeesHelper = new ListViewHelperEmployeesPopup(tfEmployee, point);
		
		employeesHelper.show(btn.getScene().getWindow());
	
	} catch(Exception exc) {
		exc.printStackTrace();
		Alert alert = new Alert(AlertType.ERROR, "Error creating employees popup; exiting");
		alert.showAndWait();
		btn.getScene().getWindow().hide();  // close and implicit exit
	}
}
 
源代码20 项目: latexdraw   文件: SaveDrawingTest.java
@Override
protected void commonCanDoFixture() {
	final SystemUtils utils = Mockito.mock(SystemUtils.class);
	Mockito.when(utils.getPathTemplatesDirUser()).thenReturn("");
	SystemUtils.setSingleton(utils);
	ui = Mockito.mock(JfxUI.class);
	statusWidget = Mockito.mock(Label.class);
	progressBar = Mockito.mock(ProgressBar.class);
	mainstage = Mockito.mock(Stage.class);
	file = Mockito.mock(File.class);
	modifiedAlert = Mockito.mock(Alert.class);
	openSaveManager = Mockito.mock(OpenSaver.class);
	fileChooser = Mockito.mock(FileChooser.class);
	currentFolder = Optional.empty();
	injector = Mockito.mock(Injector.class);
	prefService = Mockito.mock(PreferencesService.class);
	Mockito.when(injector.getInstance(PreferencesService.class)).thenReturn(prefService);
	cmd = new SaveDrawing(true, true, currentFolder, fileChooser, injector,
		file, openSaveManager, progressBar, ui, statusWidget, mainstage, modifiedAlert);
}
 
源代码21 项目: MyBox   文件: FxmlStage.java
public static void alertWarning(Stage myStage, String information) {
    try {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle(myStage.getTitle());
        alert.setHeaderText(null);
        alert.setContentText(information);
        alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.setAlwaysOnTop(true);
        stage.toFront();

        alert.showAndWait();
    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
源代码22 项目: tcMenu   文件: NewItemDialog.java
public NewItemDialog(Stage stage, MenuTree tree, CurrentProjectEditorUI editorUI, boolean modal) {
    try {
        FXMLLoader loader = new FXMLLoader(NewItemDialog.class.getResource("/ui/newItemDialog.fxml"));
        BorderPane pane = loader.load();
        controller = loader.getController();
        controller.initialise(new MenuIdChooserImpl(tree), editorUI);

        createDialogStateAndShow(stage, pane, "Create new item", modal);

    }
    catch(Exception e) {
        Alert alert = new Alert(Alert.AlertType.ERROR, "Error creating form", ButtonType.CLOSE);
        alert.setHeaderText("Error creating the form, more detail is in the log");
        alert.showAndWait();

        logger.log(ERROR, "Unable to create the form", e);
    }
}
 
源代码23 项目: tcMenu   文件: MenuEditorApp.java
private void createDirsIfNeeded() {
    var homeDir = Paths.get(System.getProperty("user.home"));
    try {
        Path menuDir = homeDir.resolve(".tcmenu/logs");
        if(!Files.exists(menuDir)) {
            Files.createDirectories(menuDir);
        }
        Path pluginDir = homeDir.resolve(".tcmenu/plugins");
        if(!Files.exists(pluginDir)) {
            Files.createDirectories(pluginDir);
        }
    } catch (IOException e) {
        Alert alert = new Alert(AlertType.ERROR, "Error creating user directory", ButtonType.CLOSE);
        alert.setContentText("Couldn't create user directory: " + e.getMessage());
        alert.showAndWait();
    }
}
 
源代码24 项目: HubTurbo   文件: DialogMessage.java
public static boolean showYesNoWarningDialog(String title, String header, String message,
                                             String yesButtonLabel, String noButtonLabel) {

    Alert alert = new Alert(Alert.AlertType.WARNING);
    alert.setTitle(title);
    alert.setHeaderText(header);
    alert.setContentText(message);

    ButtonType yesButton = new ButtonType(yesButtonLabel, ButtonBar.ButtonData.YES);
    ButtonType noButton = new ButtonType(noButtonLabel, ButtonBar.ButtonData.NO);
    alert.getButtonTypes().setAll(yesButton, noButton);

    Optional<ButtonType> result = alert.showAndWait();

    return result.get().equals(yesButton);
}
 
源代码25 项目: pikatimer   文件: FXMLRaceDetailsController.java
public void deleteWave(ActionEvent fxevent){
    // Make sure the wave is not assigned toanybody first
    final Wave w = waveStartsTableView.getSelectionModel().getSelectedItem();
    
    BooleanProperty inUse = new SimpleBooleanProperty(false);
    
    ParticipantDAO.getInstance().listParticipants().forEach(x ->{
        x.getWaveIDs().forEach(rw -> {
            if (w.getID().equals(rw)) {
                inUse.setValue(Boolean.TRUE);
                //System.out.println("Wave " + w.getWaveName() + " is in use by " + x.fullNameProperty().getValueSafe());
            }
        });
    });
    
    if (inUse.get()) {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Unable to Remove Wave");
        alert.setHeaderText("Unable to remove the selected wave.");
        alert.setContentText("The wave currently has assigned runners.\nPlease assign them to a different wave before removing.");

        alert.showAndWait();
    } else {
        raceDAO.removeWave(w); 
    }
}
 
源代码26 项目: JetUML   文件: EditorFrame.java
/**
 * If a user confirms that they want to close their modified graph, this method
 * will remove it from the current list of tabs.
 * 
 * @param pDiagramTab The current Tab that one wishes to close.
 */
public void close(DiagramTab pDiagramTab) 
{
	if(pDiagramTab.hasUnsavedChanges()) 
	{
		Alert alert = new Alert(AlertType.CONFIRMATION, RESOURCES.getString("dialog.close.ok"), ButtonType.YES, ButtonType.NO);
		alert.initOwner(aMainStage);
		alert.setTitle(RESOURCES.getString("dialog.close.title"));
		alert.setHeaderText(RESOURCES.getString("dialog.close.title"));
		alert.showAndWait();

		if (alert.getResult() == ButtonType.YES) 
		{
			removeGraphFrameFromTabbedPane(pDiagramTab);
		}
	}
	else
	{
		removeGraphFrameFromTabbedPane(pDiagramTab);
	}
}
 
/**
 * Called when the "Add" button is clicked. Adds a statistic definition to the table.
 */
@FXML
private void addSelectedStatisticDefinition() {
  // get the selected field and statistic from the combo boxes
  String selectedFieldName = fieldNameComboBox.getSelectionModel().getSelectedItem();
  String selectedStatisticType = statisticTypeComboBox.getSelectionModel().getSelectedItem();
  // check that a statistic definition with that field and statistic type is not already in the table
  if (statisticDefinitionsTableView.getItems().stream().filter(row -> row.getFieldName().equals(selectedFieldName) && row
      .getStatisticType().name().equals(selectedStatisticType)).collect(Collectors.toList()).isEmpty()) {
    // add the statistic definition to the table
    statisticDefinitionsTableView.getItems().add(new StatisticDefinition(selectedFieldName, StatisticType.valueOf(selectedStatisticType)));
  } else {
    new Alert(Alert.AlertType.WARNING, "The selected combination has already been chosen.").show();
  }
}
 
源代码28 项目: constellation   文件: JsonIODialog.java
/**
 * *
 * Present a dialog allowing user to select an entry from a list of
 * available files.
 *
 * @param names list of filenames to choose from
 * @return the selected element text or null if nothing was selected
 */
public static String getSelection(final String[] names) {
    final Alert dialog = new Alert(Alert.AlertType.CONFIRMATION);
    final ObservableList<String> q = FXCollections.observableArrayList(names);
    final ListView<String> nameList = new ListView<>(q);

    nameList.setCellFactory(p -> new DraggableCell<>());
    nameList.setEditable(false);
    nameList.setOnMouseClicked(event -> {
        if (event.getClickCount() > 1) {
            dialog.setResult(ButtonType.OK);
        }
    });
    ButtonType removeButton = new ButtonType("Remove");
    dialog.getDialogPane().setContent(nameList);
    dialog.getButtonTypes().add(removeButton);
    dialog.setResizable(false);
    dialog.setTitle("Preferences");
    dialog.setHeaderText("Select a preference to load.");

    // The remove button has been wrapped inside the btOk, this has been done because any ButtonTypes added
    // to an alert window will automatically close the window when pressed. 
    // Wrapping it in another button can allow us to consume the closing event and keep the window open.
    final Button btOk = (Button) dialog.getDialogPane().lookupButton(removeButton);
    btOk.addEventFilter(ActionEvent.ACTION, event -> {
        JsonIO.deleteJsonPreference(nameList.getSelectionModel().getSelectedItem());
        q.remove(nameList.getSelectionModel().getSelectedItem());
        nameList.setCellFactory(p -> new DraggableCell<>());
        dialog.getDialogPane().setContent(nameList);
        event.consume();
    });
    final Optional<ButtonType> option = dialog.showAndWait();
    if (option.isPresent() && option.get() == ButtonType.OK) {
        return nameList.getSelectionModel().getSelectedItem();
    }

    return null;
}
 
源代码29 项目: pcgen   文件: OptionsPathDialogController.java
@FXML
private void doChooser(final ActionEvent actionEvent)
{
	DirectoryChooser directoryChooser = new DirectoryChooser();
	String modelDirectory = model.directoryProperty().getValue();
	if (!modelDirectory.isBlank())
	{
		directoryChooser.setInitialDirectory(new File(model.directoryProperty().getValue()));
	}

	File dir = directoryChooser.showDialog(optionsPathDialogScene.getWindow());

	if (dir != null)
	{
		if (dir.listFiles().length > 0)
		{
			Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
			alert.setTitle("Directory Not Empty");
			alert.setContentText("The folder " + dir.getAbsolutePath() + " is not empty.\n"
					+ "All ini files in this directory may be overwritten. " + "Are you sure?");
			Optional<ButtonType> buttonType = alert.showAndWait();
			buttonType.ifPresent(option -> {
				if (option != ButtonType.YES)
				{
					return;
				}
			});
		}
		model.directoryProperty().setValue(dir.getAbsolutePath());
	}
}
 
源代码30 项目: G-Earth   文件: Authenticator.java
private static boolean askForPermission(NetworkExtension extension) {
    boolean[] allowConnection = {true};

    final String connectExtensionKey = "allow_extension_connection";

    if (ConfirmationDialog.showDialog(connectExtensionKey)) {
        boolean[] done = {false};
        Platform.runLater(() -> {
            Alert alert = ConfirmationDialog.createAlertWithOptOut(Alert.AlertType.WARNING, connectExtensionKey
                    ,"Confirmation Dialog", null,
                    "Extension \""+extension.getTitle()+"\" tries to connect but isn't known to G-Earth, accept this connection?", "Remember my choice",
                    ButtonType.YES, ButtonType.NO
            );

            if (!(alert.showAndWait().filter(t -> t == ButtonType.YES).isPresent())) {
                allowConnection[0] = false;
            }
            done[0] = true;
            if (!ConfirmationDialog.showDialog(connectExtensionKey)) {
                rememberOption = allowConnection[0];
            }
        });

        while (!done[0]) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return allowConnection[0];
    }

    return rememberOption;
}
 
 类所在包
 同包方法