Question

Simple question:

Can a swing frame be completely modal ( block all others windows ) ?

I tried the following, but I can still click on other apps windows ( like this browser )

JDialog myDialog  = .... 
myDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

Plase paste some code if this is possible.

Was it helpful?

Solution

JFrame is not designed to be modal. Use JDialog for it, but you will loose some JFrame functionality doing so. If you can't live with the loss, you have to block the EventQueue and replace it with your own to only accept events from the blocking one.

See Creating Modal Internal Frames for an explanation using internal frames that should be applicable to JFrame also.

Edit: Oups, my answer seems a bit off, since your code example shows you are already using a Dialog subclass for this.

OTHER TIPS

Dialogs are not meant to be globally modal. Every modern OS strongly discourages global modality in its HIG, and they may even have deprecated the functionality (as indicated by the fact that you can't get it to work). Your app should never steal events from the entire system; that's not only bad design, it's near-criminal in my book.

Ignoring the fact that most people like to multi-task between several apps, what about the scenario where you open a globally modal dialog and then your application freezes? Ctrl+Alt+Del should work on Windows to kill the app, but I'm not sure about Cmd+Opt+Escape on Mac with a globally modal dialog (does Cocoa even have global modality?). None of the Linux platforms have any nice way of killing apps which have taken over complete control of the UI as you are suggesting (you would have to kill X11 completely and start a new instance from scratch).

My answer: find another way. I don't care what your client is asking for, they don't want this.

I don't know about global modal, but here's an idea.

  1. Take the screenshot of the desktop.
  2. Go full screen.
  3. Pop up your dialog.

Since the desktop is fake screenshot, you can ignore any attempt to click into it.

Full screen sample:

private void toggleFullScreenWindow() {
  GraphicsEnvironment graphicsEnvironment
    = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice graphicsDevice
    = graphicsEnvironment.getDefaultScreenDevice();
  if(graphicsDevice.getFullScreenWindow()==null) {
    dialog.dispose(); //destroy the native resources
    dialog.setUndecorated(true);
    dialog.setVisible(true); //rebuilding the native resources
    graphicsDevice.setFullScreenWindow(dialog);
  }else{
    graphicsDevice.setFullScreenWindow(null);
    dialog.dispose();
    dialog.setUndecorated(false);
    dialog.setVisible(true);
    dialog.repaint();
  }
  requestFocusInWindow();
}

FYI: Full-Screen Exclusive Mode API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top