1

I have created an application in which a new JFrame displays certain output.

The application is working fine when I call the method new ServerInitiator().Initialize(8081) from a console application.

But when I call the method from a button click event in first frame the second frame is blank and does not display any output.

Code on first JFrame is

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {        
    new ServerInitiator().initialize(8081);
}

Code for ServerInitiator is

public class ServerInitiator {

private JFrame frame = new JFrame();

private JDesktopPane desktop = new JDesktopPane();

public static void main(String args[]){

}

public void initialize(int port){

    try {            
        ServerSocket sc = new ServerSocket(port);
        //Show Server GUI
        drawGUI();
        //Listen to server port and accept clients connections
        while(true){
            Socket client = sc.accept();
            System.out.println("New client Connected to the server");
            //Per each client create a ClientHandler
            new ClientHandler(client,desktop);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

/*
 * Draws the main server GUI
 */
public void drawGUI(){
        frame.add(desktop,BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Show the frame in a maximized state
        frame.setExtendedState(frame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
        frame.setVisible(true);
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
sourabhgkr
  • 89
  • 4
  • 10

1 Answers1

3

It's simple. You run your endless loop, which has blocking operation sc.accept(), from the event dispatch thread (EDT). The EDT is responsible for drawing UI and you shouldn't ever do any long-term operations there.

Put your socket handling code into separete thread.

Kojotak
  • 2,020
  • 2
  • 16
  • 29
  • Hi,Thanks for reply. But my application is working fine when I call Initialize() method from a console application.But now I want to call this method from a new JFrame from buttonclick event. – sourabhgkr Mar 31 '14 at 10:28
  • It's bad idea to run endless loop from event handler's thread! If you want to read just once from socket, consider using SwingWorker: move your initialization code into doInBackground() method and update the GUI in done() method. If you need to continuously read some data from socket, move the initialization code into main() method and from the main thread, update the GUI with code wrapped into `SwingUtilities.invokeLater`. – Kojotak Mar 31 '14 at 10:41
  • That happens because when you run 'stanalone' `ServerInitiator` it doesn't run from `EDT`. Add next line `System.out.println(SwingUtilities.isEventDispatchThread());` before calling `drawGUI();` and you'll see when that run from `EDT`. – alex2410 Mar 31 '14 at 10:41