mikera
mikera

Reputation: 106351

Creating a custom modal dialog for a Swing applet / application

I'm writing a Swing application that needs to function either as an applet in a browser or as a standalone application, i.e. it may be contained in either a JFrame or a JApplet.

In this context, I'd like to display a custom modal dialog box to the user (i.e. a complex dialog with a custom layout and logic, not just one of the simple JOptionPane prompts). It is fine if the dialog is a lightweight component fully contained within the application window.

At the same time, there will be background processing happening in the application (network threads, animations etc.). This needs to continue while the dialog is displayed.

What would be the best approach to implement this?

Upvotes: 2

Views: 1450

Answers (2)

GPAshka
GPAshka

Reputation: 103

Here interesting method for showing frames as modal to specified owner is described: Show the given frame as modal to the specified owner

However, start() method of class EventPump should be modified in such way:

protected void start() throws Exception
{
    Class<?> cl = Class.forName("java.awt.Conditional");
    Object conditional = Proxy.newProxyInstance(cl.getClassLoader(), new Class[] { cl }, this);

    ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
    String name = Thread.currentThread().getName();
    EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();

    Constructor constructor = Class.forName("java.awt.EventDispatchThread").
            getDeclaredConstructor(ThreadGroup.class, name.getClass(), eventQueue.getClass());
    constructor.setAccessible(true);
    Object eventDispatchThread = constructor.newInstance(threadGroup, name, eventQueue);

    Method pumpMethod = eventDispatchThread.getClass().getDeclaredMethod("pumpEvents", cl);
    pumpMethod.setAccessible(true);
    pumpMethod.invoke(eventDispatchThread, conditional);
}    

Upvotes: 1

Devon_C_Miller
Devon_C_Miller

Reputation: 16518

Take a look at JDialog. If you set it modal it will run its own event processing to keep the GUI up to date, while capturing mouse and keyboard events for its own use.

I've looked at the code it uses and it's really not something you want to try to reinvent.

If you run it non modal, you 'll probably need to add a listener to be called when it finally closes. That is done with addWindowListener and a WindowAdapter that overrides windowClosing.

As for the owner parameter for the constructor, I use

    Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, comp);

where comp is some visible component.

It works because there is always a top level Window, whether running as an applet or application.

Upvotes: 4

Related Questions