Java swing GUI冻结 [英] Java swing GUI freezes

查看:308
本文介绍了Java swing GUI冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用套接字编写Java客户端/服务器GUI应用程序,这里是问题:



我有一个按钮开始侦听指定的端口: p>

按钮actionPerformed方法

  private void listenButtonActionPerformed(java.awt.event。 ActionEvent evt){
int port = Integer.parseInt(portTextfield.getText(),10);

try {
socket.listen(port);
} catch(IOException ex){
}
}

这是socket.listen方法

  public void void()throws IOException {
ServerSocket ss = new ServerSocket港口);

while(true)
new socket(ss.accept());
}

socket类扩展线程

之后ss.accept()返回一个值,它在单独的线程中创建新的套接字实例。



点击按钮后,GUI冻结,因为在socket.listen方法中有一个无限循环。

解决方案

您的设计中有两个缺陷:


  1. ss.accept()是一个阻止调用,因此您的UI将冻结,直到有一个传入连接

  2. 不要在EDT中运行 while(true)循环。

请执行以下操作:




  • 当按钮被单击创建一个线程将开始侦听传入连接。

  • 每当你有一个传入连接,创建另一个线程,将接收传入的客户端连接并处理它。 / li>

I am writing a Java client/server GUI application using sockets and here is the problem:

I have a button to start listening for a specified port:

button actionPerformed method

private void listenButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    int port = Integer.parseInt(portTextfield.getText(), 10);

    try {
        socket.listen(port);
    } catch (IOException ex) {
    }
}

Here is the socket.listen method

public static void listen() throws IOException {
    ServerSocket ss = new ServerSocket(port);

    while (true)
        new socket(ss.accept());
}

"socket" class extends "Thread"
So after ss.accept() returns a value it creates new socket instance in separate thread.

After clicking the button the GUI freezes because inside the socket.listen method there is an infinite loop. How can I avoid that?

解决方案

You have two pitfalls in your design:

  1. ss.accept() is a blocking call so your UI will freeze until there is an incoming connection
  2. Never run while(true) loops in the EDT.

Instead do the following:

  • When the button is clicked create a thread that will start listening for incoming connections.
  • Whenever you have an incoming connection, create another thread that will take the incoming client connection and deal with it.

这篇关于Java swing GUI冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆