Java远程桌面管理

时间:2015-10-05 04:15:31

标签: java swing serversocket

我正在开发Java远程桌面管理。当我单独运行服务器启动器主类时,它工作正常。但是当我从一个按钮的动作事件中调用该类时,框架就会冻结并显示黑屏......代码就是这样。任何帮助?

import java.awt.BorderLayout;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class ServerInitiator {
    //Main server frame
    private JFrame frame = new JFrame();
    //JDesktopPane represents the main container that will contain all
    //connected clients' screens
    private JDesktopPane desktop = new JDesktopPane();

    public static void main(String args[]){
        String port = JOptionPane.showInputDialog("Please enter listening port");
       new ServerInitiator().initialize(Integer.parseInt(port));
    }

    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);
    }
}

1 个答案:

答案 0 :(得分:3)

您的while循环可能在事件调度线程的上下文中运行,阻止它处理任何新事件(包括重绘事件)

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();
    }
}

有关详细信息,请参阅Concurrency in Swing

相反,如果您希望能够更新UI(简单安全),则应使用其他Thread启动服务器或使用SwingWorker。有关详细信息,请参阅Worker Threads and SwingWorker