How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?
Asked Answered
P

10

87

How do I create and show common dialogs (Error, Warning, Confirmation) in JavaFX 2.0? I can't find any "standard" classes like Dialog, DialogBox, Message or something.

Painful answered 29/11, 2011 at 11:28 Comment(2)
Perhaps you like to have a look on project for private use: github.com/4ntoine/JavaFxDialog/wikiHyperopia
Backport of JavaFX 8 dialogs to JDK7: github.com/BertelSpA/openjfx-dialogs-jdk7Buckskins
S
123

Recently released JDK 1.8.0_40 added support for JavaFX dialogs, alerts, etc. For example, to show a confirmation dialog, one would use the Alert class:

Alert alert = new Alert(AlertType.CONFIRMATION, "Delete " + selection + " ?", ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
alert.showAndWait();

if (alert.getResult() == ButtonType.YES) {
    //do stuff
}

Here's a list of added classes in this release:

Shul answered 5/3, 2015 at 20:38 Comment(5)
Found this to be a good solution, I didn't find a way to title the top of the dialogue but not a big deal. But then again, would you need too...? CheersMonkish
@GideonSassoon The alert object can be modified after creation. A call to alert.setTitle() before showAndWait() should do nicely.Shul
Excelente solution without including external libsCottonweed
@GideonSassoon You can set the header text with alert.setHeaderText("header text"); if that is what you needInexactitude
SImple et précis ! Merci ^^Rasp
W
51

EDIT: dialog support was added to JavaFX, see https://mcmap.net/q/237461/-how-to-create-and-show-common-dialog-error-warning-confirmation-in-javafx-2-0


There were no common dialog support in a year 2011. You had to write it yourself by creating new Stage():

Stage dialogStage = new Stage();
dialogStage.initModality(Modality.WINDOW_MODAL);

VBox vbox = new VBox(new Text("Hi"), new Button("Ok."));
vbox.setAlignment(Pos.CENTER);
vbox.setPadding(new Insets(15));

dialogStage.setScene(new Scene(vbox));
dialogStage.show();
Whiffen answered 29/11, 2011 at 12:9 Comment(9)
Hmm, may be, they will appear later like FileChooser? Or they wish every developer to reinvent the wheel?)Painful
Ready standard dialogs project for JavaFX 2.0. Works for mePainful
Official platform support for Alert dialog can be tracked via javafx-jira.kenai.com/browse/RT-12643Boorman
@Painful can you show an example of how to use your dialog? thanks!Faina
@Painful Smirnov I am using your dialogs contributed on github. Excellent work and a boon to every JavaFX programmer - be blessed!Faina
I think they don't want the use of dialogs. The usage of dialogs is not a good practice.Necroscopy
Sadly Antons Dialogs are not allowed for commercial applications :(Saidee
VBoxBuilder is deprecated now. This is still a useful answer though it could do with a small update.Isidor
A Java 7 compatible solution is shown here: #14168564Consentient
B
40

Update

Official standard dialogs are coming to JavaFX in release 8u40, as part of the implemenation of RT-12643. These should be available in final release form around March of 2015 and in source code form in the JavaFX development repository now.

In the meantime, you can use the ControlsFX solution below...


ControlsFX is the defacto standard 3rd party library for common dialog support in JavaFX (error, warning, confirmation, etc).

There are numerous other 3rd party libraries available which provide common dialog support as pointed out in some other answers and you can create your own dialogs easily enough using the sample code in Sergey's answer.

However, I believe that ControlsFX easily provide the best quality standard JavaFX dialogs available at the moment. Here are some samples from the ControlsFX documentation.

standard dialog

command links

Boorman answered 17/7, 2013 at 7:34 Comment(3)
Voted up, but documentation links aren't apparent on the site linked. Also site says maven 8.0.2 is up, but for me only works with maven 8.0.1.. and I get an "Unsupported major.minor version 52.0" when calling Dialogs.create().message("great").showConfirm();Redouble
Documentation links work fine for me. The documentation currently states "Important note: ControlsFX will only work on JavaFX 8.0 b102 or later." Likely you are trying to run ControlsFX against an incompatible Java version. If you have further issues you should log them against the ControlsFX issue tracker.Boorman
Good luck finding the documentation for this library.Tessellated
A
13

Sergey is correct, but if you need to get a response from your home-spun dialog(s) for evaluation in the same block of code that invoked it, you should use .showAndWait(), not .show(). Here's my rendition of a couple of the dialog types that are provided in Swing's OptionPane:

public class FXOptionPane {

public enum Response { NO, YES, CANCEL };

private static Response buttonSelected = Response.CANCEL;

private static ImageView icon = new ImageView();

static class Dialog extends Stage {
    public Dialog( String title, Stage owner, Scene scene, String iconFile ) {
        setTitle( title );
        initStyle( StageStyle.UTILITY );
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        setResizable( false );
        setScene( scene );
        icon.setImage( new Image( getClass().getResourceAsStream( iconFile ) ) );
    }
    public void showDialog() {
        sizeToScene();
        centerOnScreen();
        showAndWait();
    }
}

static class Message extends Text {
    public Message( String msg ) {
        super( msg );
        setWrappingWidth( 250 );
    }
}

public static Response showConfirmDialog( Stage owner, String message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Confirm.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button yesButton = new Button( "Yes" );
    yesButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.YES;
        }
    } );
    Button noButton = new Button( "No" );
    noButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.NO;
        }
    } );
    BorderPane bp = new BorderPane();
    HBox buttons = new HBox();
    buttons.setAlignment( Pos.CENTER );
    buttons.setSpacing( 10 );
    buttons.getChildren().addAll( yesButton, noButton );
    bp.setCenter( buttons );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, new Message( message ) );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
    return buttonSelected;
}

public static void showMessageDialog( Stage owner, String message, String title ) {
    showMessageDialog( owner, new Message( message ), title );
}
public static void showMessageDialog( Stage owner, Node message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Info.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button okButton = new Button( "OK" );
    okButton.setAlignment( Pos.CENTER );
    okButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
        }
    } );
    BorderPane bp = new BorderPane();
    bp.setCenter( okButton );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, message );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
}

}

Aetolia answered 3/10, 2012 at 23:4 Comment(3)
Was trying to run your class but the compiler chokes on Layout - apparently the constants used. Which import did you use?Faina
How does one get the response i.e. which button was selected? the member variable buttonSelected is private.Faina
got it to compile and made buttonSelected public but calling it like this does not display anything. ` Stage stage = new Stage(StageStyle.TRANSPARENT); FXOptionPane.showConfirmDialog(stage, "Do you wish to disconnect?", "my title"); `Faina
D
8

Adapted from answer here: https://mcmap.net/q/243200/-popup-message-boxes

javafx.scene.control.Alert

For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.

import javafx.scene.control.Alert
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
    {
        /* By specifying a null headerMessage String, we cause the dialog to
           not have a header */
        infoBox(infoMessage, titleBar, null);
    }

    public static void infoBox(String infoMessage, String titleBar, String headerMessage)
    {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle(titleBar);
        alert.setHeaderText(headerMessage);
        alert.setContentText(infoMessage);
        alert.showAndWait();
    }
}

One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

or

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");
Doubleganger answered 10/6, 2015 at 14:7 Comment(4)
Please don't post identical answers to multiple questions. Post one good answer, then vote/flag to close the other questions as duplicates. If the question is not a duplicate, tailor your answers to the question.Undoubted
@MartijnPieters The original question specifies Swing as a tag but is open to general Java dialogs (it was asked before JavaFX was really a thing), if anything the JavaFX content I posted there is slightly off topic, yet useful to newbies who find that Q&A while looking for Java Dialogs and don't realise that Swing is going out of date.Doubleganger
All the more reason then to tailor your answer to the context then!Undoubted
I found this topic on google, so it's better to have information right here than to enter question topic to see the answer i need. This answer deserves more votes.Annis
C
7

This works since java 8u40:

Alert alert = new Alert(AlertType.INFORMATION, "Content here", ButtonType.OK);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.show();
Cutanddried answered 29/4, 2016 at 12:34 Comment(1)
Keep in mind that this has to be run in the FXApplicationThread. (Eg. with Platform.runLater() or similar)Colcothar
C
4

Update: JavaFX 8u40 includes simple Dialogs and Alerts!, check out this blog post which explains how to use the official JavaFX Dialogs!


Coz answered 16/5, 2013 at 8:45 Comment(0)
G
3

You can give dialog box which given by the JavaFX UI Controls Project. I think it will help you

Dialogs.showErrorDialog(Stage object, errorMessage,  "Main line", "Name of Dialog box");
Dialogs.showWarningDialog(Stage object, errorMessage,  "Main line", "Name of Dialog box");
Goya answered 17/7, 2013 at 6:53 Comment(3)
There are no such dialog classes in JavaFX 2.xBoorman
javafx-dialogs-0.0.3.jar You can download this jar and then you can work with the same dialog box.Goya
I edited your post to link to the 3rd party JavaFX dialogs project Rajeev referenced. I think it is an older version of the dialogs from ControlsFX.Boorman
M
2
public myClass{

private Stage dialogStage;



public void msgBox(String title){
    dialogStage = new Stage();
    GridPane grd_pan = new GridPane();
    grd_pan.setAlignment(Pos.CENTER);
    grd_pan.setHgap(10);
    grd_pan.setVgap(10);//pading
    Scene scene =new Scene(grd_pan,300,150);
    dialogStage.setScene(scene);
    dialogStage.setTitle("alert");
    dialogStage.initModality(Modality.WINDOW_MODAL);

    Label lab_alert= new Label(title);
    grd_pan.add(lab_alert, 0, 1);

    Button btn_ok = new Button("fermer");
    btn_ok.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            // TODO Auto-generated method stub
            dialogStage.hide();

        }
    });
    grd_pan.add(btn_ok, 0, 2);

    dialogStage.show();

}



}
Mneme answered 30/5, 2014 at 21:55 Comment(1)
It's probably a good idea to at least explain what your code is doing; there's fairly strong opinions on whether or not code-only answers are okay.Weakkneed
K
1

To make an example of Clairton Luz work, you need to run in the FXApplicationThread and insert into Platform.runLater method your code snippet:

  Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                        alert.setTitle("Error Dialog");
                        alert.setHeaderText("No information.");

                        alert.showAndWait();
                    }
            );

Otherwise, you'll get: java.lang.IllegalStateException: Not on FX application thread

Kg answered 22/2, 2020 at 2:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.