Reputation: 71
See the example code below. After clicking the example button a few times, how to find the last dialog opened ? This is a real use-case. A user has opened one or two modal dialogs and has clicked a button starting a long running background task in the last dialog and has then switched to another application during that background task is running. On completion, the task should display a notification window with the correct dialog as the parent so that when switching back to the application, that notification window is shown on top of the correct dialog.
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Example
{
private JDialog createDialog( final Window parent, final int count )
{
final JDialog dialog = new JDialog( parent, "Dialog " + count );
dialog.setModal( true );
dialog.getContentPane().setLayout( new FlowLayout() );
final JButton button = new JButton( "Open Dialog " + ( count + 1 ) );
button.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( final ActionEvent e )
{
final JDialog nextDialog = createDialog( dialog, count + 1 );
nextDialog.pack();
nextDialog.setLocationRelativeTo( dialog );
nextDialog.setVisible( true );
}
} );
dialog.getContentPane().add( button );
return dialog;
}
public static void main( final String[] arguments )
{
SwingUtilities.invokeLater( new Runnable()
{
@Override
public void run()
{
final Example example = new Example();
final JDialog dialog = example.createDialog( null, 1 );
dialog.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
dialog.pack();
dialog.setLocationRelativeTo( null );
dialog.setVisible( true );
}
} );
}
}
Upvotes: 1
Views: 710
Reputation: 347334
You could use KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow()
which will, obviously, return the window which current contains the component with the current keyboard focus...
Upvotes: 2