applet中的start()方法删除面板

Exo*_*mus 2 java user-interface applet swing event-dispatch-thread

我做了一个小程序.我曾经JPanel设置applet的内容,我在init()方法中start()做,在做其他的事情.当我运行applet时没有包含start()一切正常并且内容出现,但是如果我添加了start()方法,则applet不会显示内容.

这是为什么?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JApplet;
import javax.swing.JEditorPane;
import javax.swing.JPanel;


public class Server extends JApplet {

final static int port = 4444;
ServerSocket listen;
JEditorPane message;
JPanel content;

    public void init(){
        message = new JEditorPane();
        message.setText("Listening...");
        message.setEditable(false);
        message.setVisible(true);

        content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(message, BorderLayout.NORTH);

        setContentPane(content);
    }

    public void start(){    
         try {
             listen = new ServerSocket(port);
             while(true){   
                Socket client = listen.accept();    
                HandleConnection hc= new HandleConnection(client);
            }

            } catch (IOException e) {
              System.out.println("Couldn't listen on port "+port);
        }
        }

    public void stop(){}
    public void destroy(){}
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

你正在用你的while (true)块踩踏Swing事件线程.因为这个线程(也称为事件调度线程或EDT)负责所有GUI的图形和用户交互,所以在其上运行长时间运行的代码将有效地完全冻结GUI.解决方案:不要在事件线程上执行此操作,而是在后台线程(例如SwingWorker对象提供的线程)中执行此操作.有关这方面的更多信息,请阅读Swing中的Concurrency.