如何在没有连接客户端的情况下在GUI服务器中显示组件?

时间:2013-11-26 10:09:01

标签: java swing user-interface jframe

我有一个名为Version3的选项卡式Jframe,它实现了Runnable。进入它我有3个JPanels在不同的tabbs.Next到那些选项卡我有一个textarea。 我希望我的GUI能够监听消息并在textarea中显示它们。我试图让我的GUI Version3成为一个服务器,它会在收到来自客户端的任何消息时一直监听。

java.awt.EventQueue.invokeLater(new Runnable(){
     public void run(){
          Version3 v=new Version3();
          v.setVisible(true);
          v.listenTo();
      }
});

我将GUI Version3作为服务器,但是当我运行程序时,GUI的组件在连接到客户端之前不会显示。我只有一个没有组件的空白GUI窗口。有没有想法如何在没有连接客户端的情况下在我的GUI上显示所有组件?

2 个答案:

答案 0 :(得分:1)

  

我将GUI Version3作为服务器,但是当我运行程序时   GUI的组件在连接到客户端之前不会显示.I   只有一个没有组件的空白GUI窗口。任何想法如何   在没有连接客户端的情况下在我的GUI上显示我的所有组件?

我认为当你的班级尝试连接到客户端时,你很可能会阻止Event Dispatching Thread(a.k.a. EDT)。这就是为什么它在你有连接时起作用的原因,但是当你没有连接时却没有。 EDT是一个单独的特殊线程,可以在其中创建和更新Swing组件。如果您在EDT中运行繁重的任务,那么您的GUI将冻结,Swing组件将无法工作(甚至无法显示)。

查看Concurrency in Swing路径,了解Swing中的并发性。

偏离主题:请考虑在以后的问题中添加您的代码。正如@ alex2410建议,如果你包含SSCCE来证明你的问题,那就更好了。

答案 1 :(得分:0)

服务器

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Server extends JPanel {

    Socket socket;
    final static int PORT = 2325;
    PrintWriter pr;
    public ServerSocket serverSocket;
    JButton btn_sendHello;
    int counter;

    Thread thread;

    public Server() {

        counter = 0;
        btn_sendHello = new JButton("Send hello");
        btn_sendHello.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (pr != null) {
                    pr.println("Hello from server " + ++counter);
                }
            }
        });

        this.add(btn_sendHello);

        try {
            serverSocket = new ServerSocket(PORT);
           thread = new Thread(waitingClient);
           thread.start();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    Runnable waitingClient = new Runnable() {
        @Override
        public void run() {
            try {
                socket = serverSocket.accept();
                openStreams();
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };

    private void openStreams() {
        if (socket != null) {
            try {
                pr = new PrintWriter(socket.getOutputStream(), true);
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setTitle("Server");
                frame.add(new Server());
                frame.pack();
                frame.setSize(250, 100);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

<强>客户端:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Client extends JPanel {

    final static int PORT = 2325;
    private Socket socket;
    private BufferedReader fromServer;
    private JTextField jtfield;
    Thread threadReceive;

    public Client() {
        jtfield = new JTextField(12);
        this.add(jtfield);

        try {
            socket = new Socket("localhost", PORT);
            openStreams();
            Thread thread = new Thread(receives);
            thread.start();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    Runnable receives = new Runnable() {
        @Override
        public void run() {
            while (true) {
                synchronized (this) {
                    if (socket != null) {
                        processServerInput();
                    }
                }
            }
        }
    };

    private void openStreams() {
        try {
            if (socket != null) {
                fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            }
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void processServerInput() {
        try {
            String line = fromServer.readLine();
            while (!(line.equals("Bye"))) {
                jtfield.setText(line);
                line = fromServer.readLine();
            }
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void closeStreams() {
        try {
            fromServer.close();
            socket.close();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setTitle("Client");
                frame.add(new Client());
                frame.pack();
                frame.setSize(250, 100);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}