请参阅下面的示例代码。单击几次示例按钮后,如何找到最后打开的对话框?这是一个真实的用例。用户已打开一个或两个模态对话框,并在最后一个对话框中单击了一个启动长时间运行后台任务的按钮,然后在该后台任务运行期间切换到另一个应用程序。完成后,任务应显示一个通知窗口,其中正确的对话框作为父对象,以便在切换回应用程序时,该通知窗口显示在正确的对话框之上。
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 );
}
} );
}
}
答案 0 :(得分:2)
您可以使用KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow()
,这显然会返回当前包含当前键盘焦点的组件的窗口...