Search code examples
javaswingjoptionpanethread-sleep

Get modal dialog instance swing


I have an application if I click on button1 it will show a modal dialog dialog1 (But I don't have instance of the dialog1.), as well it will initiate a Thread, where in the thread does some processing, and mid of the Thread processing while in dialog1 the Thread wants to show an alert maybe the server is not connected. But the focus is not above the dialog1. It is loading as sibling to dialog1. Is there any way to show the alert to child of dialog1

Here is the sample.

public class Main1 extends javax.swing.JFrame {

Thread show = null;
private javax.swing.JButton jButton1;

public Main1() {
    setBounds(0, 0, 500, 500);
    jButton1 = new javax.swing.JButton("Button1");
    jButton1.setBounds(10, 10, 100, 30);
    jButton1.setVisible(true);
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            show.start();
            //For Example I'm having this. I have a function call which will create and show a dialog similar to this. 
            java.awt.Frame frame = new java.awt.Frame();
            JDialog dialog1 = new JDialog(frame, true);
            dialog1.setBounds(20, 20, 300, 300);

            dialog1.show();
        }
    });
    getContentPane().add(jButton1);
    getContentPane().setLayout(null);
    show = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                shoe();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    });
    setDefaultCloseOperation(2);

}

private void shoe() {
    JOptionPane.showMessageDialog(this, "HEELO");
}

public static void main(String... f) {
    new Main1().setVisible(true);
}
}

Is there anyway to get the child modal instance of the Main1 in any means? So that I can provide that instance to the JOptionPane.showMessageDialog(this, "HEELO"); instead the this or any other way to achieve this?

Correct me, if my understanding is wrong. Pardon me if this is duplicate.


Solution

  • Wow, finally sorted it out. From the help of the question Get Any/All Active JFrames in Java Application?

    I got the active window from the list and gave that as parent

    private void shoe() {
        Component parent = this;
        Window[] allWindows = Window.getWindows();
        for(Window window : allWindows){
            //Validate and find the appropriate window by its instance name or someother mean
            parent  = window;
         }
    
        JOptionPane.showMessageDialog(parent, "HEELO");
    }