Blocking the Interface in Netbeans

Asked

Viewed 155 times

1

I’m developing a program for client-server communication. I am developing the graphical interface of the program based on JPanel/Forms.

The client data is sent correctly to the server. My problem is when I go to fetch the server data back to the client, the graphical interface blocks, and no elements are shown that should appear.

Client

package Interfaces;

import Classes.Mensagem;
import Classes.Utilizador;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Zé Luís
 */
public class ConversaGrupo extends javax.swing.JFrame {

    private static Utilizador userClass;
    private String serverID;
    private Socket socket = null;
    private int port = 2048;
    private String host;
    private Utilizador utilizador;
    private Mensagem mensagemServidor;
    private static PrintWriter out = null;
    private static BufferedReader in = null;

    private static String mensagemServidorThr;

    /**
     * Creates new form ConversaGrupo
     */
    public ConversaGrupo(Utilizador cd, String serverID) {
        this.userClass = cd;
        this.serverID = serverID;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList<>();
        jButton2 = new javax.swing.JButton();
        text_toClienteEscrever = new javax.swing.JTextField();
        enviar_Button = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        areaChat = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(230, 230, 230));

        jButton1.setText("CRIAR GRUPO");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jList1.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jList1);

        jButton2.setText("MENSAGEM PRIVADA");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout
                    .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 
                                      javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(jButton2)
                .addContainerGap(16, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 301, 
                              javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        enviar_Button.setText("ENVIAR");
        enviar_Button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enviar_ButtonActionPerformed(evt);
            }
        });

        jButton4.setText("SAIR");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        areaChat.setColumns(20);
        areaChat.setRows(5);
        areaChat.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                areaChatMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(areaChat);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(text_toClienteEscrever, 
                            javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(enviar_Button, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
                            .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 
                                          javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jScrollPane3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 
                              javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 333, 
                              javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(text_toClienteEscrever, javax.swing.GroupLayout.PREFERRED_SIZE, 
                                  40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(enviar_Button)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)))
                .addContainerGap(25, Short.MAX_VALUE))
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, 
                          javax.swing.GroupLayout.DEFAULT_SIZE, 
                          javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void areaChatMouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
    }

    private void formWindowOpened(java.awt.event.WindowEvent evt) {

        areaChat.setText("BEM-VINDO \t" + userClass.getNome());
        connectServer();

        try {
            receberDadosServidor();
        } catch (IOException ex) {
            Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

    }

    private void enviar_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        //verifica se a caixa de texto está vazia
        if (text_toClienteEscrever.getText() != null) { 
            //envia para o servidor a mensagem que o user escreveu
            out.println(userClass.getNome() + ":" + text_toClienteEscrever.getText()); 
            out.flush();
            text_toClienteEscrever.setText("");
        }

    }

    private void connectServer() {

        try {
            socket = new Socket(host, port);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            areaChat.setText(areaChat.getText() + "\nLigação com o servidor estabelecida!\n");

            text_toClienteEscrever.requestFocus();

        } catch (IOException ex) {
            areaChat.setText(areaChat.getText() + "\n Erro com o servidor\n");

        }

    }

    private void receberDadosServidor() throws IOException {
        String fromServer = null;
        while ((fromServer = in.readLine())!= null) {
            System.out.println("Servidor: " + fromServer);
            areaChat.setText(areaChat.getText() + "\n" + fromServer);


        }

    }

    // Variables declaration - do not modify
    private javax.swing.JTextArea areaChat;
    private javax.swing.JButton enviar_Button;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JList<String> jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField text_toClienteEscrever;
    // End of variables declaration 
}

The widget window opens, but problems start when the program enters the method directly formWindowsOpened().

When you enter the method and with Debugger you pass through the lines, but you block and don’t see the message "WELCOME" as you can see on the line areaChat.setText("BEM-VINDO \t" + userClass.getNome());.

The interface blocks, and only by stopping the server and client execution can I get the windows to close.

I know it has to do with the method receberDadosServidor() but I don’t understand why, from Interface, block.

private void receberDadosServidor() throws IOException {
    String fromServer = null;
    while ((fromServer = in.readLine())!= null) {
        System.out.println("Servidor: " + fromServer);
        areaChat.setText(areaChat.getText() + "\n" + fromServer);
    } 


private void formWindowOpened(java.awt.event.WindowEvent evt) {

    areaChat.setText("BEM-VINDO \t" + userClass.getNome());
    connectServer();

    try {
        receberDadosServidor();
    } catch (IOException ex) {
        Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Server side

import Classes.Utilizador;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Classe responsável por albergar o servidor do programa.
 *
 * @author Zé Luís
 */
public class server {

    /**
     * O servidor corre quando antige o método main.
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        ServerSocket srvSckt = null;
        int porto = 2048;
        boolean listening = true;

        //conecao ao servidor
        try {
            srvSckt = new ServerSocket(porto);
            System.out.println("Conecção ao Servidor efectuada com sucesso!");
        } catch (IOException ex) {
            System.err.println("Impossível coneção a porta \t" + porto);
        }

        Socket clientSocket = null;
        clientSocket = srvSckt.accept(); //espera por pedidos de clientes.

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
                true);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));

        String fromServerIntoServer = null;

        //  out.println(in.readLine());
        while (listening) {

            out.println(in.readLine());

        }
        srvSckt.close();
        clientSocket.close();
        out.close();
        in.close();  

    }

}

Below I leave the example of the Graphical Interface, where in TextArea nothing appears. Everything is locked and I can only close the window if I stop running the script. Interface onde na TextArea não aparece nenhum elemento nem texto

Solution I added a Thread to the client class so there is no competition between the interface and the socket.

 Thread recever = new Thread() {
        public void run() {
            try {
                receberDadosServidor();
            } catch (IOException ex) {
                Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
    recever.start();

Full class

 private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  

        areaChat.setText("BEM-VINDO \t" + userClass.getNome());
        connectServer();

        //devido a concorrencia de recursos, necessitamos de uma thread.
              Thread recever = new Thread() {
                public void run() {
                    try {
                        receberDadosServidor();
                    } catch (IOException ex) {
                        Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            recever.start();


    }                                 
  • Please provide a [mcve] to make it possible to execute the code and simulate the problem.

  • This image does not help to make the code executable. If you provide a [mcve] of your code, makes it very easy to help you.

  • OK, I’ll be right there.

  • already found a solution, I added a thread because of the competition between the coneccao and the interface.

  • 1

    Good, then answer with the solution found :)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.