JavaFX how can I reset the application? - java

my code opens another window but the first one is still open. How can I close the first window?
ButtonType continue = new ButtonType("Continue");
ButtonType exit= new ButtonType("Exit");
alert.getButtonTypes().setAll(continue, exit);
Optional<ButtonType> result = alert.showAndWait();
if (result .get() == continue ) {
Controllerxx = new commandCenter();
centerFX newFX= new centerFX ();
Stage stage = new Stage();
newFX.start(stage);
} else if (result .get() == exit) {
Platform.exit();
}

You can try something like below :
btn.setOnAction((ActionEvent event) -> {
((Node) (event.getSource())).getScene().getWindow().hide();
});
You can get the current scene by the Action event of your exit button and close it.

Related

Dialogue in javafx [duplicate]

This question already has answers here:
Alert Box For When User Attempts to close application using setOnCloseRequest in JavaFx
(2 answers)
Closed 4 years ago.
I want to implement a dialogue alert when the user clicks the close button. With the option for yes they do want to leave and no they don't.
Button button = new Button("Exit");
gridPane.add(button, 12, 12);
button.setOnAction(e ->{
primaryStage.close();
});
How would I go about this?
Use the onCloseRequest event of the stage for closing the window using the X button of the window:
private static boolean confirmClose() {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setContentText("Do you really want to close the app?");
return alert.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK;
}
primaryStage.setOnCloseRequest(event -> {
if (!confirmClose()) {
event.consume();
}
});
Note that this event is not triggered when closing the window programmatically. You need to request user confirmation yourself in such a case:
button.setOnAction(evt -> {
if (confirmClose()) {
primaryStage.close();
}
});
You have a pretty good article which explains et give some examples about Alert
The one you need is a Confirmation-Dialog :
button.setOnAction(e ->
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Exit Application");
alert.setHeaderText("Exit of the App");
alert.setContentText("Do you really want to exit ? ");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
primaryStage.close();
Platform.exit();
System.exit(0);
} else {
// ... user chose CANCEL or closed the dialog
}
});
Try something like:
Button button = new Button("Exit");
gridPane.add(button, 12, 12);
button.setOnAction(e ->{
if(confirmDialog(
"Sure you want to quit?",
"Sure you want to quit?",
"We're really closing - click yes to quit, no to stay in the app")
) {
primaryStage.close();
}
});
...
public boolean confirmDialog(String title, String headerText, String message) {
Alert alert = new Alert(AlertType.CONFIRMATION, message, ButtonType.YES, ButtonType.NO);
alert.initModality(Modality.APPLICATION_MODAL);
alert.initOwner(scene); //scene must be accessible as a field
alert.setTitle(title);
alert.setHeaderText(headerText);
ButtonType result = alert.showAndWait().orElse(ButtonType.NO);
return ButtonType.YES==result;
}

Changing the cursor in an alertbox JavaFX

Hi I am trying to change the cursor, in a JavaFX alert which displays once a button in sceneHome is pressed, once a buttontype is clicked.
This is the function thats gets called when the user presses the button in sceneHome:
public void export() {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Export menu");
alert.setHeaderText("Wat wilt u exporteren, adressen of ritten?");
alert.setContentText("Maak een keuze.");
ButtonType buttonTypeOne = new ButtonType("Adressen");
ButtonType buttonTypeTwo = new ButtonType("Ritten");
ButtonType buttonTypeCancel = new ButtonType("Annuleren", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOne){
//scene.setCursor(Cursor.WAIT);
ToCSV.export("adressen");
//scene.setCursor(Cursor.DEFAULT);
} else if (result.get() == buttonTypeTwo) {
//scene.setCursor(Cursor.WAIT);
ToCSV.export("ritten");
//scene.setCursor(Cursor.DEFAULT);
} else{
//do nothing
}
}
If I say sceneHome.setCursor(Cursor.WAIT) nothing happens and if I say alert.getDialogPane().getScene().setCursor(Cursor.WAIT) I get a NullPointerException...
So which scene should I pass in (at //scene.setCursor(Cursor.DEFAULT); and //scene.setCursor(Cursor.WAIT);)?
It looks like your ToCSV.export call actually block the program to change the cursor. Try to run execution of this method in separate Task:
private static void export(Scene scene) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Export menu");
alert.setHeaderText("Wat wilt u exporteren, adressen of ritten?");
alert.setContentText("Maak een keuze.");
ButtonType buttonTypeOne = new ButtonType("Adressen");
ButtonType buttonTypeTwo = new ButtonType("Ritten");
ButtonType buttonTypeCancel = new ButtonType("Annuleren", ButtonBar.ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOne){
scene.setCursor(Cursor.WAIT);
final Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
ToCSV.export("adressen");
return null;
}
#Override
protected void succeeded() {
scene.setCursor(Cursor.DEFAULT);
}
};
new Thread(task).start();
} else if (result.get() == buttonTypeTwo) {
//
} else{
//do nothing
}
}
The scene is the one where the button that opens this dialog located.
Ideally, for the clean code sake, you should create a separate ToCSVTask class with this logic and submit it to ExecutorService - you may google the cleanest way how to do it.

if no item of a combobox is selected do semothing in Java Fx

I am using JavaFX have a list of items in a combobox , when a user trys to register i want that a condition cheks if he selected an item or not in that combo. i have tryed this but it doesent work , how to do it please .
public void ADDuser(ActionEvent event) {
String username = usernametf.getText();
String pass = passtf.getText();
LocalDate datebirth = dateofbirth.getValue();
String situation = situationcombobox.getSelectionModel().getSelectedItem().toString();
if (!username.equals("") &&
!pass.equals("") &&
!datebirth.equals(null) &&
!situation.equals(null)) {// situaion problem
mainc.con.AdduserDatabase(username, pass, datebirth, situation, gender);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Ajout");
alert.setHeaderText(null);
alert.setContentText("Ajout réussi merci " );
alert.showAndWait();
Stage stage = (Stage) btnadd.getScene().getWindow();
stage.close();
} else {
System.out.println(situation);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Ajout");
alert.setHeaderText(null);
alert.setContentText("Please Fill All the fields ! " );
alert.showAndWait();
}
}
}

javafx: bug when trying to close window properly

I am designing the close window functionality for my desktop application. A high level explanation of the functionality is listed:
If I click the Exit menuItem, it prompts a ConfirmBox the user to confirm whether he wants to save or not before closing the application.
If the user click on the CloseButton on the window to force close the window (i.e. setOnCloseRequest function), the Exit menuItem event is fire off, which brings the user to case (1) again.
Within my ConfirmBoxcode, I have bind ENTER key to save things, N key to not save things and ESCAPE key to close confirmBox.
I have also set accelerator for the Exit menuItem (METAKEY + E).
Everything works fine. However, there is a minor bug if I follow this special sequence of steps. Whenever I use the accelerator for the Exit menuItem (i.e. METAKEY + E) and then I press either one of the 3 keys(ENTER, ESCAPE, N), the confirmBox closes but it pops up again.
I am wondering why is this happening only in this very special case?
public class ConfirmBox {
// answer[0] determines the need to Save
// answer[1] determines whether to close the application or not
private static boolean[] answer = new boolean[]{false,false};
private static Stage window;
public static boolean[] displayWarning(String title, String message){
window = new Stage();
window.initModality(Modality.APPLICATION_MODAL);
window.setTitle(title);
window.setMinWidth(300);
Label label = new Label();
label.setText(message);
Button yesButton = new Button("Yes");
Button noButton = new Button("No");
// needToSave = true, close Application = true and close this confirmbox
yesButton.setOnAction(ey ->{
answer[0] = true;
answer[1] = true;
window.close();
});
// needToSave = false, close Application = true and close this confirmbox
noButton.setOnAction(en -> {
answer[0] = false;
answer[1] = true;
window.close();
});
// needToSave = false, close Application = false and close this confirmbox
window.setOnCloseRequest(e -> {
answer[0] = false;
answer[1] = false;
closeConfirmBox();
});
// key binding
window.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if ( e.getCode() == KeyCode.N){
noButton.fire();
e.consume();
}
});
// bind enter key to yesButton
window.addEventHandler(KeyEvent.KEY_PRESSED, ev -> {
if (ev.getCode() == KeyCode.ENTER ){
yesButton.fire();
ev.consume();
}
});
window.addEventFilter(KeyEvent.KEY_PRESSED, ev ->{
if(ev.getCode()==KeyCode.ESCAPE){
ev.consume();
answer[0] = false;
answer[1] = false;
closeConfirmBox();
}
});
VBox layout = new VBox(20);
layout.setPadding(new Insets(20,5,20,5));
HBox bottomLayout = new HBox(50);
bottomLayout.setPadding(new Insets(20,5,20,5));
bottomLayout.getChildren().addAll(yesButton,noButton);
bottomLayout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(label,bottomLayout);
layout.setAlignment(Pos.CENTER);
Scene scene = new Scene(layout);
window.setScene(scene);
window.showAndWait();
return answer;
}
public static void closeConfirmBox(){
window.close();
}
}
Within my controller class, this is how I designed my MenuItem menuItemExit.
menuItemExit.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
//System.out.println("set stage" + primaryStage);
boolean[] answer;
boolean needToSave = false;
boolean closeApplication = false;
if(saved.get() == false){
answer = ConfirmBox.displayWarning("Warning", "Do you want to save your stuff?");
needToSave = answer[0];
closeApplication = answer[1];
}
if(needToSave == true){
menuItemSave.fire();
}
if(closeApplication== true){
Platform.runLater(new Runnable() {
public void run() {
close();
}
});
}
}
});
primaryStage.setOnCloseRequest(e -> {
e.consume();
menuItemExit.fire();
});
menuItemExit.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.META_DOWN));
public void close(){
this.primaryStage.close();
}

JavaFX Alert Dialog Cancel Button

I made a JavaFX alert dialog box to prompt the user, asking if they want to save the output from the console before closing the application.
I have the yes and no options taken care of. If the user clicks cancel, I want it to just close the dialog box and leave everything open. As of right now, if I hit cancel it will close the GUI.
Here is my code for overriding the close button on the GUI.
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent event)
{
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText("Would You Like To Save Your Console Output?");
alert.setContentText("Please choose an option.");
ButtonType yesButton = new ButtonType("Yes");
ButtonType noButton = new ButtonType("No");
ButtonType cancelButton = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(yesButton, noButton, cancelButton);
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == yesButton)
{
Main.setConsoleVisible();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
else if(result.get() == noButton)
{
System.exit(0);
}
else if(result.get() == cancelButton)
{
}
}
});
Both in "yesButton" and "cancelButton" if-blocks consume the CloseRequest WindowEvent:
else if(result.get() == cancelButton)
{
event.consume();
}
Use Platform.exit() instead of System.exit(0).
Use primaryStage.close(); instead of System.exit(0);
From the documentation for onCloseRequest:
Called when there is an external request to close this Window. The installed event handler can prevent window closing by consuming the received event.
Be aware that result.get() will throw an exception if the user closes the alert dialog without pressing any buttons. The Dialog documentation explains this thoroughly.

Categories

Resources