Java Code Examples for javafx.scene.control.Alert

The following examples show how to use javafx.scene.control.Alert. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: pcgen   Author: PCGen   File: RadioChooserDialog.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
}
 
Example #2
Source Project: markdown-writer-fx   Author: JFormDesigner   File: FileEditorTabPane.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
}
 
Example #3
Source Project: pikatimer   Author: PikaTimer   File: FXMLEventController.java    License: GNU General Public License v3.0 6 votes vote down vote up
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();
    }
}
 
Example #4
Source Project: pmd-designer   Author: pmd   File: SimplePopups.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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();
}
 
Example #5
Source Project: uip-pc2   Author: abdelgmartinezl   File: Resumen.java    License: MIT License 6 votes vote down vote up
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();
}
 
Example #6
Source Project: uip-pc2   Author: abdelgmartinezl   File: Resumen.java    License: MIT License 6 votes vote down vote up
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();
}
 
Example #7
Source Project: MyBox   Author: Mararsh   File: SettingsController.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #8
Source Project: pikatimer   Author: PikaTimer   File: FXMLEventController.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #9
Source Project: phoebus   Author: ControlSystemStudio   File: ScanEditor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example #10
Source Project: Online-Food-Ordering-System   Author: winston-dsouza   File: TakeOrderController.java    License: MIT License 6 votes vote down vote up
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;
    }
    
}
 
Example #11
Source Project: ShootOFF   Author: phrack   File: Main.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example #12
Source Project: Online-Food-Ordering-System   Author: winston-dsouza   File: MenuController.java    License: MIT License 6 votes vote down vote up
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;
    }
    
}
 
Example #13
Source Project: MythRedisClient   Author: Kuangcp   File: ZsetAction.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 修改值.
 *
 * @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();
    }
}
 
Example #14
Source Project: zest-writer   Author: firm1   File: ImageInputDialog.java    License: GNU General Public License v3.0 6 votes vote down vote up
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();
    }
}
 
Example #15
Source Project: trex-stateless-gui   Author: cisco-system-traffic-generator   File: ProfileStreamNameDialogController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source Project: latexdraw   Author: latexdraw   File: NewDrawingTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #17
Source Project: blobsaver   Author: airsquared   File: Background.java    License: GNU General Public License v3.0 6 votes vote down vote up
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");
}
 
Example #18
/**
 * 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);
  }
}
 
Example #19
Source Project: examples-javafx-repos1   Author: bekwam   File: ListViewHelperMainController.java    License: Apache License 2.0 6 votes vote down vote up
@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
	}
}
 
Example #20
Source Project: latexdraw   Author: latexdraw   File: SaveDrawingTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #21
Source Project: MyBox   Author: Mararsh   File: FxmlStage.java    License: Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #22
Source Project: tcMenu   Author: davetcc   File: NewItemDialog.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #23
Source Project: tcMenu   Author: davetcc   File: MenuEditorApp.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #24
Source Project: HubTurbo   Author: HubTurbo   File: DialogMessage.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #25
Source Project: pikatimer   Author: PikaTimer   File: FXMLRaceDetailsController.java    License: GNU General Public License v3.0 6 votes vote down vote up
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); 
    }
}
 
Example #26
Source Project: JetUML   Author: prmr   File: EditorFrame.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #27
/**
 * 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();
  }
}
 
Example #28
Source Project: constellation   Author: constellation-app   File: JsonIODialog.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * *
 * 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;
}
 
Example #29
Source Project: pcgen   Author: PCGen   File: OptionsPathDialogController.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@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());
	}
}
 
Example #30
Source Project: G-Earth   Author: sirjonasxx   File: Authenticator.java    License: MIT License 5 votes vote down vote up
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;
}