Search code examples
javaswingjdialog

Child JDialog appears blank when opened from parent jdialog


My swing code is as below. I have to use setAlwaysOnTop(true) for all jdialogs for some requirement in the project. If i use so the child dialogs which is launched from parent dialogs will appear blank until it is resized with mouse manually.

Please let me know if this can be resolved in any way.

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class Test {
    static JFrame f;
    public static void main(String[] args)
    {
        Test t = new Test();
        t.getFrame().show();
    }
    public JFrame getFrame(){
        f = new JFrame("frame");
        JPanel p = new JPanel();
        JButton b = new JButton("click");
        b.addActionListener(new ActionListener()
        {
            public void actionPerformed( ActionEvent e )
            {
                String s = e.getActionCommand();
                if (s.equals("click")) {
                    JDialog d = new JDialog(f, "dialog Box");
                    d.setLayout( new FlowLayout() );
                    JButton b1 = new JButton ("OK");
                    d.add( new JLabel ("Click button to continue."));
                    d.add(b1);
                    d.setSize(300,300);
                    d.setAlwaysOnTop(true);
                    b1.addActionListener(new ActionListener()
                    {
                        public void actionPerformed( ActionEvent e1 )
                        {
                            String s1 = e1.getActionCommand();
                            if (s1.equals("OK")) {
                                JDialog d1= new JDialog(f, "child dialog Box", Dialog.ModalityType.DOCUMENT_MODAL);
                                JLabel l1 = new JLabel("this is a child dialog box");
                                d1.add(l1);
                                d1.setAlwaysOnTop(true);
                                d1.setSize(200, 200);
                                d1.setVisible(true);
                            }
                        }
                    });
                    d.setVisible(true);
                }
            }
        });
        p.add(b);
        f.add(p);
        f.setSize(400, 400);
        return f;
    }
}

When the dialog is launched

When the dialog is launched

When it is resized with mouse manually

When it is resized with mouse manually


Solution

  • The owner of JDialog d1 is not the JFrame f but the other JDialog d.
    Change this line of your code:

    JDialog d1= new JDialog(f, "child dialog Box", Dialog.ModalityType.DOCUMENT_MODAL);
    

    to this:

    JDialog d1= new JDialog(d, "child dialog Box", Dialog.ModalityType.DOCUMENT_MODAL);