Karthik
Karthik

Reputation: 63

new thread not showing the frame

I am trying to establish a network connection and the details are in a JFrame. When user clicks a button, it should start the new thread and should show the wait message to the user until, the main thread establish a network connection. I wrote this code

 public void actionPerformed(ActionEvent arg0) {
     Thread ref = new Thread(new Test());//Create a new thread
     ref.start();
      new AIDRTConnManager().createConnection(ipAddress, portAddress);//main thread
      }



//This is my Thread Class
    public class Test implements Runnable{
    JDialog waitDialog;
    JPanel panel1 = new JPanel();
    JLabel waitLabel;
    JFrame frame;


    public void run(){
        frame = new JFrame();
         waitDialog = new JDialog( frame,AIRDT.toolName, true );
         waitDialog.setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE );  
         JLabel waitLabel = new JLabel( "Trying to Connect to PleaseWait...",ErrorDialog.icon,SwingConstants.CENTER ); 
            panel1.add( waitLabel ); 
            waitDialog.add( panel1 );  
            waitDialog.setSize( 100, 40 ); 
            waitDialog.setBounds( 500,300, 300, 80 ); 
        waitDialog.setVisible( true ); 
    }
}

But when I click the button, the Jdialog shows the empty frame, without the wait message (JLable) and once I done with the network connection, this wait message shows properly.

Where I am going wrong? Is this a Swing Issue (Or) Thread Issue?

Could you please help me to show a wait message until the completion of back end activity?

Upvotes: 1

Views: 894

Answers (2)

ajshort
ajshort

Reputation: 3764

You're mixing up your threads here - all operations that interact with the UI, such as creating a new frame, must occur on the Event Dispatch Thread (EDT), or the "main" thread as you call it. Background tasks should be performed on a different thread.

Basically you have it backwards - you should perform the background work in the new thread, and create the new frame in the main thread, which is the opposite way to how you have it now.

Upvotes: 3

Dan D.
Dan D.

Reputation: 32391

The code under the actionPerformed executes under the Event Dispatch Thread (EDT), not on the main thread as you say in the comment.

This means that as long as the connection thing happens, the EDT is blocked, so it doesn't have to chance to process some other UI stuff like displaying your JDialog.

Also, not related to the issue, but please note that you create a JFrame that is never displayed and that is the parent of your JDialog.

Upvotes: 3

Related Questions