As of this writing, the answer is no. It is weird that the Java FX team did not include classes that developers can easily call to display message alerts like those in the JOptionPane class.

The workaround? Create your own. Well, the Java FX team did release a JAR file of a few classes, alert dialogs included but these look horrible. So the only solution was for me to create my own.

This is what I came up with.

 

I know, it looks simple. But you can easily make it look better using CSS. I only provided the basic for you to get started.

Here are the codes.

And this is the css file.

To use it, just call it like this:

If you check the class, there is a method called getImage(). You will have to find your own error and info icons though ;).

The alert dialog will have a height of 100 pixels. If you put a long text, there is no need to worry because the alert dialog will expand in width while maintaining a max of 2 lines ;).

Lastly, the last few lines of the constructor are needed so that the alert dialog will always stay at the center on top of its parent Stage.

The nice thing about Java FX is how CSS can easily be used to style the user interface. Making rounded corners on a window looks tedious when done programmatically.

However, with the use of CSS, this can easily be done.

Easy, right?

Well, there is no solution to making a Stage window modal when opened from a JFrame. At least not directly. I scoured through countless forums and blog posts but their solutions never made it modal.

A future version of Java FX may solve this problem. In the meantime, this is how I did it in Java FX 2. The same JDialog will be instantiated but set to invisible. I did this by calling the setUndecorated() method to true.

Within the JDialog class, that is where I called the Java FX code to open a Stage window dialog.

So now it is modal. But when you click the JFrame in the task bar in the Windows OS below, the Stage window is not sent to the front. This is not the behavior we want for a modal window, right?

What I did was to add a FocusListener in the JDialog custom class so that when it is in focus (since it is modal), it will call the Stage window object and send it to the front.

Here is the custom JDialog class I made. 

 
Then just call that from within your JFrame.

The StageModalDialog class is a custom class I made that inherits from the Stage class.

Related Posts Plugin for WordPress, Blogger...