Search code examples
javaswingjdialog

two dialogs setAlwaysOnTop(true): the second generated one is behind the first one


I have a JDialog which can generate another one. The two JDialogs have the property setAlwaysOnTop(true) and aren't modal. The second Jdialog generated from the first one appears always behind. I would like it to appear in front.

I tried several things : toFront(), requestFocus(), etc..

Here a short example to reproduce the problem:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;


public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
       final JDialog modelDialog = createDialog();
       modelDialog.setVisible(true);
   }

   private static JDialog createDialog(){
      final JDialog modelDialog = new JDialog();
      modelDialog.setBounds(132, 132, 300, 200);
      Container dialogContainer = modelDialog.getContentPane();
      dialogContainer.setLayout(new BorderLayout());
      JPanel panel1 = new JPanel();
      JButton okButton = new JButton("Ok");
      okButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
             final JDialog modelDialog = createDialog();
             modelDialog.setVisible(true);
         }
      });
      panel1.add(okButton);
      dialogContainer.add(panel1, BorderLayout.SOUTH);
      
      modelDialog.setAlwaysOnTop(true);
      
      return modelDialog;
   }

enter image description here

enter image description here

After a click on the OK button, we see another dialog appearing behind the current one. The new dialog has the focus but is still behind


Solution

  • Actually, I tried your code, and it is no problem appears. If you want to see it too clearly, create dialog with random location. In every click, new dialog is random place on the top.

    modelDialog.setBounds(new Random().nextInt(400), new Random().nextInt(400), 300, 200);
    

    But my suggestion is create dialog as modal, in addition to set old one as parent.