我创建了一个应用程序,其中一个新的 JFrame
显示特定的输出。
当我从控制台应用程序调用方法 new ServerInitiator().Initialize(8081)
时,应用程序工作正常。
但是当我从第一帧中的按钮单击事件调用该方法时,第二帧是空白的并且不显示任何输出。
第一个 JFrame
上的代码是
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new ServerInitiator().initialize(8081);
}
ServerInitiator
的代码是
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);
}
}
最佳答案
很简单。您从事件分派(dispatch)线程 (EDT) 运行无限循环,它具有阻塞操作 sc.accept()
。 EDT 负责绘制 UI,您不应该在那里进行任何长期操作。
将套接字处理代码放入单独的线程中。
关于java - 从第一帧调用时第二帧不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22759023/