c_user89
c_user89

Reputation: 53

how can i display components in GUI server without a connected client?

I have a tabbed Jframe named Version3 which implements Runnable. Into it i have 3 JPanels in different tabbs.Next to those tabs i have a textarea. I want my GUI to listen for messages and display them in the textarea. I tried to make my GUI Version3 a server which listens all the time in case it receives any message from client.

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

I made my GUI Version3 a server but when i run the program the components of the GUI doesn't show until it's connected to client.I just have a blank GUI window with no components. Any ideas how to display all my components on my GUI without a client connected?

Upvotes: 1

Views: 220

Answers (2)

Saleh Feek
Saleh Feek

Reputation: 2076

Server:

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

Client:

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

Upvotes: 0

dic19
dic19

Reputation: 17971

I made my GUI Version3 a server but when i run the program the components of the GUI doesn't show until it's connected to client.I just have a blank GUI window with no components. Any ideas how to display all my components on my GUI without a client connected?

I think it's more than likely that you're blocking the Event Dispatching Thread (a.k.a. EDT) while your class is trying to connect to the client. That's the reason why it works when you have connection but it doesn't when you haven't. The EDT is a single and special thread where Swing component creation and updates take place. If you have a heavy task running in the EDT then your GUI will freeze and Swing components won't be able to work (or even display).

Take a look to Concurrency in Swing trail to learn about concurrency in Swing.

Off-topic: please consider add your code in future questions. As @alex2410 suggested it's better if you include a SSCCE demonstrating your problem.

Upvotes: 1

Related Questions