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);
Related
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.
I'm trying to make an overlay on the screen using JavaFX and an issue I'm having is that whenever my overlay pops up, it steals focus from whichever program I'm currently in. The issue with this is that my overlay allows the user to simulate keyboard key presses using the robot class (like an on-screen keyboard) and without keeping the focus in the original window, the typed characters have nowhere to go. I've tried setting the modality to none, but that's also the default option and it doesn't seem to be doing anything. Would putting my JavaFX scene in a JFrame work or is there some better way to do it only in JavaFX?
Try this
when focused -> compute what you want to
then call Stage.toBack(); //the currently focused window prior to yours will gain focus back
Im trying to make a java program that will popup/notify me to stop what I am currently doing and do something. more like a reminder. My question is how will I make a pop up in java.
I found this docs, but dont know how to implement for the parent component.
JOptionPane.showMessageDialog(??,"this is a modal dialog.");
The answer depends, do you have a parent component (like a JFrame or other component) or are you simply display the JOptionPane independently?
If you are simply displaying the JOptionPane independently, you can simply pass it null.
If you are displaying the JOptionPane as part of a large application, with windows and other components, you can simply pass it a reference of what ever component you want the JOptionPane to displayed relative to, such as the window or most accessible container/component
The parent argument (if supplied) simply allows the dialog to act as a modal (blocking) dialog for the window which contains the supplied component. This requires the user to have to dismiss the dialog before they can continue to interact with the parent window/component
Take a closer look at How to Make Dialogs for more details
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.
We have an application which, as its first UI action, displays a modal JDialog without a parent frame.
public LoginDialog(Frame owner, Config config, Object... params) {
super((Frame)null, true);
It unfortunately has the annoying characteristic that when it appears, although it comes to the front, it does not grab the focus.
So the user, after launching the application by double-clicking on the start menu, has to use the mouse to select the "login" dialog and type in information.
Is there a way to make this JDialog grab the focus when it appears in the front?
I've tried calls to "requestFocus" before, after and via invokeLater "during" the call to setVisible(true) - but none of these seems to have any effect.
How do we make a modal dialog grab the focus?
UPDATE: The issue was the code used to try to present a background "wait window". This window was displayed "behind" the login dialog as a hack so that when the dialog disappeared the user would see the "Please wait" message. As it was the first window created by the application, it got the focus. I am not sure if there would have been a way to make the dialog gain the focus again inside the event dispatch thread with this hack - but I fixed it by un-hacking it and doing things properly.
First, it a little strange that modal dialog is parent-less. The point in modal dialog is that it is displayed on its parent and does not allow to access parent.
So, the first recommendation is to make it non-modal. I believe it will work.
BTW I have just tried to create such dialog and have not problems with focus. Try probably to simplify your code:
JDialog d = new JDialog();
d.setSize(200, 200);
d.setVisible(true);
This works for me and I believe will work for you. Now start changing this simple code towords your real application code. At some point it will stop working and you will see where the problem is.
If nothing helps try to use the trick I described in this article. Look for title "Portable window activation". I hope it will help.
See Dialog Focus for a potential fix using a RequestFocusListener. I have used it successfully for setting focus in JOptionPane dialogs.
1) you have to create JDialog contents and showing container wrapped inside invokeLater()
or best and safiest way is
2) you have to set for ModalityTypes or Modal for parent
3) only one from containers could be Modal in applications lifecycle