2014-06-11 18 views
0

我正在爲我的java服務器程序製作GUI,但是當我啓動它時,程序顯示白色的JFrame並且不會將組件加載到框架中。 這裏有代碼:使用jframe的java服務器

public ServerFrame() throws SQLException, ClassNotFoundException, IOException { 
    initComponents(); 

    server = new ServerSocket(4444); 
    textList.setText("Waiting for client to connect..."); 

    SimpleDataSource.init("database.properties"); 
    net = new Network(); 

} 

public static void main(String args[]) { 

     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable(){ 
      @Override 
      public void run(){ 

       ServerFrame sf; 
       try{ 
        sf = new ServerFrame(); 
        sf.setVisible(true); 

        s = server.accept(); 
        InetAddress clientAddress = s.getInetAddress(); 
        textList.setText("Incoming connection from: " + clientAddress.getHostName() + "[" + clientAddress.getHostAddress() + "]\n"); 

        ServiceClass service = new ServiceClass(s,net); 
        Thread t = new Thread(service); 
        t.start(); 

       }catch (SQLException | ClassNotFoundException | IOException ex){ 
        Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     }); 
    } 

當程序啓動它不顯示我部件爲框架,因爲它等待客戶端連接。當客戶端連接它顯示正確的所有組件..如何顯示所有組件沒有客戶端連接?

感謝

回答

1

我不知道這些行做完全,所以出現這種情況之下可能也適用於他們。

SimpleDataSource.init("database.properties"); 
net = new Network(); 

的主要問題是最有可能的,這行:server = new ServerSocket(4444);直到客戶端連接,這使得你的應用程序的主線程繼續執行,從而顯示一切都掛起了一切。

要解決此問題,請在單獨的線程上啓動服務器。

事情是這樣:

new Thread(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       server = new ServerSocket(4444); 
      } 
     }).start(); 

你需要聲明你的服務器最終,以便它可以從run方法中進行訪問。