2015-12-27 36 views
3

我正在创建多人游戏,但是当创建ServerSocket时,我无法关闭在该应用程序中运行的任何JFrame,这里是我的服务器创建代码:在创建ServerSocket(或套接字)后,JFrame无法关闭

private void createServer() { 
     JFrame frame = new JFrame("Cow Invaders - Server"); 
     JTextArea console = new JTextArea(); 
     frame.setSize(640, 480); 
     frame.setResizable(false); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     console.setFont(new Font("Times New Roman", Font.BOLD, 15)); 
     console.setLineWrap(true); 
     frame.add(console); 
     frame.setVisible(true); 
     try { 
      server = new ServerSocket(Integer.parseInt(port)); 
      System.out.println("No problems here"); 
     } catch (IOException e) { 
      System.err.println("An error has occurred: " + e.getMessage()); 
      e.printStackTrace(); 
     } 
     console.append("Started server on port " + port + " and with an IP of " + server.getInetAddress()); 
     try { 
      socket = server.accept(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      System.err.println("An error has occurred: " + e.getMessage()); 
     } 
     console.append("\n" + "Connection from: " + socket.getInetAddress()); 
     try { 
      out = new DataOutputStream(socket.getOutputStream()); 
     } catch (IOException e) { 
      System.err.println("An error has occurred: " + e.getMessage()); 
      e.printStackTrace(); 
     } 
     try { 
      out.writeUTF("You have successfully joined the game."); 
     } catch (IOException e) { 
      System.err.println("An error has occurred" + e.getMessage()); 
      e.printStackTrace(); 
     } 
     System.out.println("Successfully send data."); 
    } 

关于是什么原因造成的?

回答

4

您似乎在单线程上执行所有操作,包括使用阻塞代码,这将阻止Swing事件线程,从而阻止它执行必要的活动。我猜测用这个代码你的JFrame会被冻结。建议:

  • 在Swing Event Dispatch Thread(EDT)上创建所有Swing调用。如果你的GUI在这个线程上启动,那么你已经设置了大部分Swing调用。
  • 在后台线程中进行所有长时间运行的任务调用。一个SwingWorker可以很好地工作,但是只要你不直接从后台线程进行Swing调用。
  • 如果您的应用程序正在创建多个子窗口,它们应该是对话窗口,如JDialogs,而不是JFrame。

查看Lesson: Concurrency in Swing了解更多信息。