Java 8 + Swing: Modal Dialog Theory - java

I am working on an application that will have the following feature:
The application will have a "Load Image" button to open an image and settings modal dialog. It will need to block until that dialog returns, either with the results of the processing or null if the user changed his mind.
The image and settings dialog will allow the user to select an image using a JFileChooser dialog and to specify to what level of detail to process the image. Clicking a "Load" button will open a load dialog.
The load dialog needs to be a custom-designed dialog that reports in detail about the time-consuming processing of the image. If the user allows the processing to finish, it needs to close and return the object back to the original dialog, which needs to close and return that object back to the application. If the user decides it is taking too long to perform the processing, he can cancel the load, closing the loading dialog and returning to the image and settings dialog.
Conceptually, this does not seem so difficult to me. However, when I try to determine how to get this to work within Swing, somehow I cannot put it together. From what I've read, GUI components need to be instantiated in Swing's event thread since many of them are not thread-safe. These same components need to block on calls similar to (but not the same as, since I need to write custom components) the JOptionPane.showInputDialog() methods. But these calls need to instantiate new components in the event thread and wait for events to occur in the event thread before returning a value to the application. Compounding this with the fact that I need a dialog to pop up from a dialog, I feel quite lost.
I have read the Java Tutorial on dialogs and several posts on StackOverflow and other sites trying to determine how I can design classes that work correctly. Somehow, I just don't understand how this can work at all (isn't the event thread going to sleep after the first blocking call?), and how I can write the custom classes I need to make this work. Frankly, I am not certain I understand my confusion enough that I was able to explain it.
Could someone please explain what goes on under the hood when modal dialogs have been instantiated? How I can write dialog classes that behave the way I need as described above?

The application will have a "Load Image" button to open an image and settings modal dialog. It will need to block until that dialog returns, either with the results of the processing or null if the user changed his mind.
OK, so this dialog will need to be modal. That much we know.
The image and settings dialog will allow the user to select an image using a JFileChooser dialog and to specify to what level of detail to process the image. Clicking a "Load" button will open a load dialog.
OK, so the load dialog will need to be modal off of the image and settings dialog. No biggie there either.
The load dialog needs to be a custom-designed dialog that reports in detail about the time-consuming processing of the image. If the user allows the processing to finish, it needs to close and return the object back to the original dialog, which needs to close and return that object back to the application. If the user decides it is taking too long to perform the processing, he can cancel the load, closing the loading dialog and returning to the image and settings dialog.
OK, so the load dialog code will need to instantiate and execute a SwingWorker to do the time-consuming image processing in a background thread, and then have the SwingWorker use its publish/process method pair to push information about the processing details back to the load dialog.
...From what I've read, GUI components need to be instantiated in Swing's event thread since many of them are not thread-safe.
Correct.
These same components need to block on calls similar to (but not the same as, since I need to write custom components) the JOptionPane.showInputDialog() methods.
And this is what a modal JDialog allows you to do. Another option to keep in mind is to use a JOptionPane and pass in a JPanel with whatever GUI you want the JOptionPane to display. JOptionPanes are surprisingly flexible and useful.
But these calls need to instantiate new components in the event thread and wait for events to occur in the event thread before returning a value to the application. Compounding this with the fact that I need a dialog to pop up from a dialog, I feel quite lost.
Again it's simple. The load dialog will call a SwingWorker which will communicate back to the load dialog.
Could someone please explain what goes on under the hood when modal dialogs have been instantiated?
Now you may be asking a bit too much for the volunteers on this site to do, since this question would probably require someone to write a complete tutorial to answer, and it has been asked and answered before, so the information should be discoverable by you. If you really want to see what is going on under the hood, you should first do the preliminary research on the subject yourself, look at the source code, and if still stuck, ask a much more specific and answerable question after first doing your own due diligence work.

Modal dialogs started from the primary event loop spawn a secondary event loop that remains active while the primary loop is blocked. See java.awt.SecondaryLoop.

Related

Advantages of InteractionDialog over Dialog?

I was recommended to use InteractionDialog rather than Dialog, but I'm failing to see the advantages. What I can see is a problem. What I need is letting the user enter a PIN or whatever and wait for their answer. This is needed both on the EDT thread (the user choose to save the PIN) and on other threads (a web page requires the PIN for login).
With Dialog,
I can call it from the EDT thread and it works nice.
When on a different thread, I can be trivially adapted by a one-liner in the callee (see getFromGui in my linked question).
With InteractionDialog,
I can use it easily from other threads via some simple wait/notifyAll magic.
I can't use it from the EDT thread, except via callbacks like okBtn.addActionListener(...), which is verbose and ugly.
So I am confused and asking:
What do I gain from the InteractionDialog?
Is there a simple way how to use it uniformly no matter what thread I am on?
There are two separate things here:
Modality
How it works
A dialog can be modal or non-modal but it isn't interactive like an InteractionDialog. The modal dialog blocks the EDT internally using InvokeAndBlock so the current thread stops until there's a response from the dialog. This is convenient but has some edge case issues. E.g. the event that launched the dialog might trigger other events that would happen after the dialog was dismissed and cause odd behavior.
But that's not the big thing in modality. Modality effectively means the form behind you "doesn't exist". Everything that matters is the content of the dialog and until that is finished we don't care about the form behind. This core idea meant that a dialog effectively derives form and as such it behaves exactly like showing another form effectively disabling the current form. What you see behind the dialog is a drawing of the previous form, not the actual form.
Text fields can pose a problem. Because the way the dialog is positioned (effectively padded into place within its form using margin) the UI can't be scrolled as text field requires when the virtual keyboard rises. Since people use dialogs in such scenarios we try to workaround most of these problems but sometimes it's very hard e.g. if the dialog has a lot of top margin, the virtual keyboard is open and covering it. Or if the user rotates the screen at which point the margin positioning the dialog becomes invalid.
Note that in InteractionDialog Some of these issues such as the margin to position also apply.
Now InteractionDialog is a completely different beast that sprung out of a completely different use case. What if we want a dialog such as a "color palette that floats on top of the ui?
We can move it from one place to another but still interact with the underlying form. That's the core use case for InteractionDialog. As such modality is no longer something we need so it was never baked into InteractionDialog although it technically could have been (but it doesn't make sense to the core use case).
It's implemented as a Container placed into the layered pane of the current form so the form around it is real. Because the form is "live" layout works better and the removal of modality makes some edge cases related to editing slightly better. There are still some inherent problems with dialog positioning and rotation though. It also allows you to click outside of the dialog while input is ongoing which might be a desirable/undesirable effect for your use case.
Overall I try to use dialogs only for very simple cases and avoid input when possible. If I use input I never use more than one field (e.g. no-username and password fields) so I won't need to scroll. These things work badly for native UIs as well e.g. with the virtual keyboard obscuring the submit button etc. Since those behaviors are very hard to get right for all resolution/virtual keyboard scenarios.
Based on the answer from Shai, I wrote a form working as the base class for most of my dialogs. Basically, it shows the content from the subclass and adds the "OK" and "Cancel" buttons.
There's a method for use from the EDT thread like
public void showAndThen(BooleanConsumer consumer) {
assert CN.isEdt();
...
okBtn.addActionListener(a -> {
lastForm.show();
consumer.accept(true);
});
cancelBtn.addActionListener(a -> {
lastForm.showBack();
consumer.accept(false);
});
}
where BooleanConsumer is a trivial void accept(boolean b) interface.
There's another method for use from other threads
#Override public final boolean ask() {
assert !CN.isEdt();
final BooleanTransfer transfer = new BooleanTransfer();
CN.callSerially(() -> showAndThen(result -> transfer.set(result)));
return transfer.await();
}
where BooleanTransfer is a two-method class where the thread calling set passes a boolean to the thread calling await.

Disable dialog close for ProgressMonitor

I'm working with Swing's ProgressMonitor.
This produces this nice dialog box for me:
Honestly, I think there's a flaw in the design of ProgressMonitor: What do you think happens if the user closes the dialog box by pressing the red/white cross ? Yep, you guessed it: It simply closes/hides the dialog and whatever job you have going in the background of course continues. There's no way to get the dialog box back, afaik.
Closing the window should either mean "cancel" or simply not be allowed, because I need the user to either wait for the task to complete or cancel it. How do I achieve either of this?
If I could just get a reference to that JDialog then I could do:
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
but I can't get that reference.
UPDATE AND FINAL ANSWER
So, I wasn't telling you the full story. In fact I use ProgressMonitorInputStream which of course under the covers use ProgressMonitor, so I thought it didn't matter for the case at hand. But it does!
Andrew is right when he says that ProgressMonitor sets the isCancelled flag when the dialog is closed. This can be verified by looking at the JDK sources. But in order to catch that event you'll need a PropertyChangeListener. When working with a ProgressMonitorInputStream you are likely not to have one (like me) because updating the ProgressMonitor is all taken care of by ProgressMonitorInputStream so you won't have to do that part yourself. I was under the assumption that ProgressMonitorInputStream's raison d'etre was in not having to do boilerplate coding.
I have to say that I find the benefits of using a ProgressMonitorInputStream to be extremely small or even negative compared to a DIY approach.
Check ProgressMonitor.isCanceled(), which indeed, the ProgressMonitorDemo does.

SWT disable window causes lose focus

I'm making custom dialogs that I want to pop up and disable the main shell behind it so that it cannot be clicked while the dialog is active.
My initial plan was something like as follows:
shell.setEnabled(false);
doDialogStuff();
shell.setEnabled(true);
this worked but as I close the dialog, it loses focus of the shell that was open before the dialog. I managed to sort of fix it by adding
shell.setFocus();
after the last line but this is messy and causes the screen to flicker as the window loses and then gains focus in a split second, also, it sometimes doesn't regain focus and I can't understand why :/
Is there a better way to disable the background window without it losing focus.
Thanks in advance SO peeps
You should create a custom dialog based on this tutorial.
This way you just have to set the modality of the dialog to whatever you need exactly and the dialog will take care of the rest for you.
This should be helpful as well (Javadoc of Shell):
The modality of an instance may be specified using style bits. The modality style bits are used to determine whether input is blocked for other shells on the display. The PRIMARY_MODAL style allows an instance to block input to its parent. The APPLICATION_MODAL style allows an instance to block input to every other shell in the display. The SYSTEM_MODAL style allows an instance to block input to all shells, including shells belonging to different applications.
The proper thing to do is create the dialog as a modal window. When you create the dialog's shell you should do something like
dialogShell = new Shell(mainShell, PRIMARY_MODAL | DIALOG_TRIM);

How to wait for a JFrame to close before continuing?

My program consists of 3 main 'sections'. Main function, Login form and App form. The main function should do something like: Open Login form, wait for it to close, then open App form. I can't get the waiting part to work, or rather, I don't know how I would go around doing that.
I was told by someone to use a JDialog instead and use setModal(true), but with that approach the Login form wouldn't appear on the taskbar, which is terrible in my opinion.
Another thing I considered was to open the App from inside the Login after it closes, but that feels like bad design since that'd make the Login form non-reusable.
So, please, what would you suggest?
Why must the login appear on the task bar, since the main app will be there, and you don't want more than one task bar item for an individual program. Your best option may be to use a modal JDialog.
Another option is to use CardLayout to swap "views".
A third option is to use a JFrame if you must but attach a listener to it, a WindowListener I believe, to respond to its close event.
Regardless of which route you go, your login gui should be a JPanel so that you can place it anywhere you wish and then change your mind later.

Progress Dialog in Swing

How can I make a modal JDialog without buttons appear for the duration it takes a Runnable instance to complete and have that instance update a progress bar/message on that dialog?
Clearly spaghetti code might work, but I'm looking for a clean design if one exists.
You might want to look into ProgressMonitor. It automatically pops up a dialog with a progress bar if the operation is taking a long time; see How to Use Progress Monitors.
Look at the project described at the following URL:
http://digilander.libero.it/carlmila/compmon/main.html
It is a free Java library alternative to the Swing ProgressMonitor.
Use a monitor class whit a global instance and which your code keeps up to date (I'm starting, I'm working, I'm at xxx%, I'm done).
The monitor can then decide to show the dialog and keep it current. Later, you can simply replace the dialog with a progress bar in the status bar, for example. Use an interface for the monitor (methods: start(), update(), end(), error(), isAborted()) so you can replace it with something else, too.
You can extend the monitor to wait for 500ms after start() if there is an end() and not show the dialog in this case, etc.
This is how Eclipse does it and it works well.

Categories

Resources