Last active
November 23, 2020 18:02
-
-
Save clartaq/419b92094e8da1f652f1 to your computer and use it in GitHub Desktop.
Creating an Alert Box that Always Appears over the Primary Stage.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package deletealertdemo; | |
import javafx.application.Application; | |
import javafx.collections.FXCollections; | |
import javafx.collections.ObservableList; | |
import javafx.event.ActionEvent; | |
import javafx.scene.Node; | |
import javafx.scene.Scene; | |
import javafx.scene.control.Alert; | |
import javafx.scene.control.Button; | |
import javafx.scene.control.ButtonType; | |
import javafx.scene.control.ListView; | |
import javafx.scene.layout.BorderPane; | |
import javafx.stage.Modality; | |
import javafx.stage.Stage; | |
import javafx.stage.Window; | |
/** | |
* From an answer given on | |
* http://stackoverflow.com/questions/33838293/how-to-set-alert-box-position-over-current-primarystage-javafx/33846225#33846225 | |
* @author david | |
*/ | |
public class DeleteAlertDemo extends Application { | |
ObservableList<String> observablePlantList; | |
ListView<String> plantList; | |
protected void handleDeleteButtonClick(ActionEvent event) { | |
String item = plantList.getSelectionModel().getSelectedItem(); | |
Alert alertBox = new Alert(Alert.AlertType.CONFIRMATION, "Confirm Delete", | |
ButtonType.OK, ButtonType.CANCEL); | |
alertBox.setContentText("Are you sure you want to delete this " | |
+ item.toLowerCase() + "?"); | |
Window owner = ((Node)event.getTarget()).getScene().getWindow(); | |
alertBox.initModality(Modality.APPLICATION_MODAL); | |
alertBox.initOwner(owner); | |
alertBox.showAndWait(); | |
if (alertBox.getResult() == ButtonType.OK) { | |
int selectedPlant = plantList.getSelectionModel().getSelectedIndex(); | |
observablePlantList.remove(selectedPlant); | |
} else { | |
alertBox.close(); | |
} | |
} | |
@Override | |
public void start(Stage primaryStage) { | |
Button deleteBtn = new Button(); | |
deleteBtn.setText("Delete"); | |
deleteBtn.setOnAction(this::handleDeleteButtonClick); | |
observablePlantList = FXCollections.observableArrayList("Begonia", | |
"Peony", "Rose", "Lilly", "Chrysanthemum", "Hosta"); | |
plantList = new ListView<>(observablePlantList); | |
plantList.getSelectionModel().select(0); | |
BorderPane root = new BorderPane(); | |
root.setCenter(plantList); | |
root.setRight(deleteBtn); | |
Scene scene = new Scene(root, 300, 250); | |
primaryStage.setTitle("Delete Alert Demo"); | |
primaryStage.setScene(scene); | |
primaryStage.show(); | |
} | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment