Package projetcs

Source Code of projetcs.ClientView

/**
* ProjetCSView.java
*/
package projetcs;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Vector;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
/**
* The application's main frame.
*/
public class ClientView extends FrameView {
  /**
   *  ---------------------------
   * METHODES publiques
   * ---------------------------
   */
  public ClientView(SingleFrameApplication app) {
        super(app);
        // initialisation des attributs
        adrServeur = new String("localhost");
        portServeur = 10002;
        nicknameUser = new String("");

        // création de la fenêtre de configuration qui serra presque invariablement appellée
        configConnectView = new ConfigConnexionView(this);
        socket = new Socket();

        // création de la fenêtre des transferts
        transfertView = new TransfertEnCoursView(this);
        initComponents();

        // une selection autorisée dans la liste
        connectesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });


  }

  @Action
  public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = ClientApp.getApplication().getMainFrame();
            aboutBox = new ProjetCSAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        ClientApp.getApplication().show(aboutBox);
  }

  /**
   *  -- ACCESSEURS
   */
  public Socket getSocket() {
        return socket;
  }

  public void setSocket(Socket socket) {
        this.socket = socket;
  }

  public String getAdrServeur() {
        return adrServeur;
  }

  public void setAdrServeur(String adrServeur) {
        this.adrServeur = adrServeur;
  }

  public String getNicknameUser() {
        return nicknameUser;
  }

  public void setNicknameUser(String nicknameUser) {
        this.nicknameUser = nicknameUser;
  }

  public long getPortServeur() {
        return portServeur;
  }

  public void setPortServeur(long portServeur) {
        this.portServeur = portServeur;
  }

  public Timer getBusyIconTimer() {
        return busyIconTimer;
  }

  public JProgressBar getProgressBar() {
        return progressBar;
  }

  public JLabel getStatusMessageLabel() {
        return statusMessageLabel;
  }

  public Communication getMyComm() {
        return myComm;
  }

  public void setMyComm(Communication myComm) {
        this.myComm = myComm;
  }

  public Vector<EtatFichierTransfert> getTransfertsEnCours() {
        return transfertsEnCours;
  }

  public void setFichiersEnCours(Vector<EtatFichierTransfert> fichiersEnCours) {
        this.transfertsEnCours = fichiersEnCours;
  }

  public TransfertEnCoursView getTransfertView() {
        return transfertView;
  }

  public Vector<String> getConnectes() {
        return connectes;
  }

  public void setConnectes(Vector<String> connectes) {
        this.connectes = connectes;
  }

  public void connexion() {

        // la connexion n'a pas encore été configurée
        if (getAdrServeur().isEmpty()
                || getNicknameUser().isEmpty()) {
            // boite de dialogue
            ConfigOkCancelDialog dial = new ConfigOkCancelDialog(this.getFrame(), true);
            ClientApp.getApplication().show(dial);
            if (dial.getReturnStatus() == 1) {
                // affichage de la fenêtre de configuration...
                ClientApp.getApplication().show(configConnectView);
            }
        } // la connexion est configurée, on peut commencer à se connecter
        else {

            try {
                // 1ere etape: etablir la connexion
                // --------------------------------
                statusMessageLabel.setText("Connexion au serveur...");
                socket = new Socket(adrServeur, (int) portServeur);


                // 2eme etape: envoie du pseudo
                // ----------------------------
                statusMessageLabel.setText("Reservation du pseudo...");
                // on créé le flux en entrée
                java.io.InputStream in = socket.getInputStream();
                DataInputStream entree = new DataInputStream(in);
                // on crée le flux en sortie
                java.io.OutputStream out = socket.getOutputStream();
                DataOutputStream sortie = new DataOutputStream(out);
                // on transmet le nickname
                sortie.writeUTF(nicknameUser);

                // on attend la réponse du serveur
                // ici on reçoit un Message (de la classe du même nom)
                Message msg = new Message();
                msg.receive(entree);



                if (msg.getType() == 1) {
                    // on nous refuse la connexion
                    statusMessageLabel.setText("Le pseudo est déjà reservé sur le serveur.");
                    // on la coupe, la connexion
                    socket.close();

                    // on propose à l'utilisateur de changer son pseudo
                    OkCancelDialog dial = new OkCancelDialog(this.getFrame(), true, "Le pseudo est déjà reservé sur le serveur :\nVoullez-vous reconfgurer la connexion ?");
                    ClientApp.getApplication().show(dial);
                    if (dial.getReturnStatus() == 1) {
                        nicknameUser = "";
                        configConnectView.setVisible(true);
                    }
                } else if (msg.getType() == 2) {
                    // on nous accepte sur le serveur
                    statusMessageLabel.setText("Connexion établie: " + nicknameUser + " sur " + socket.getInetAddress().getHostAddress());
                    nicknameText.setText(nicknameUser);
                    nicknameText.setEnabled(true);
                    infoServeurLab.setText("Vous êtes connecté sur " + socket.getInetAddress().getHostAddress());

                    // on gèle les widgets qui nous intérèssent
                    confConnexionMenuItem.setEnabled(false);
                    connexionMenuItem.setEnabled(false);
                    // on en dégèle d'autres...
                    deconnexionMenuItem.setEnabled(true);


                    // 3eme etape: on attend un message du serveur
                    // --------------------------------------------
                    attendreUnMessage(socket);

                }


            } catch (java.net.ConnectException ex) {
                if ("Connection refused".equals(ex.getMessage())) {
                    statusMessageLabel.setText("Connexion refusée par le serveur.");
                }
            } catch (UnknownHostException ex) {
                statusMessageLabel.setText("Le serveur n'existe pas à l'adresse indiquée.");
            } catch (IOException ex) {
                Logger.getLogger(ClientView.class.getName()).log(Level.SEVERE, null, ex);
            }


        }

  }

  public void deconnexion() {

        if (socket.isConnected()) {

            try {

                // on previent le serveur

                // création du flux en sortie
                java.io.OutputStream out = socket.getOutputStream();
                DataOutputStream sortie = new DataOutputStream(out);

                Message msg = new Message();
                // type 18 = deconnexion
                msg.setType((byte) 18);
                msg.send(sortie);

                // on coupe le socket
                sortie.close();
                socket.close();

                // on dégèle certain composants
                confConnexionMenuItem.setEnabled(true);
                connexionMenuItem.setEnabled(true);
                // on en gèle d'autres...
                deconnexionMenuItem.setEnabled(false);

                // on vide la liste des clients connectés
                javax.swing.DefaultListModel dlm = new javax.swing.DefaultListModel();
                connectesList.setModel(dlm);


                // on supprime tous les onglets
                for (int i = 0; (i < conversationTabPane.getTabCount()); i++) {
                    conversationTabPane.removeTabAt(i);
                }
                myTabs.removeAllElements();

                statusMessageLabel.setText("Deconnexion du serveur.");
                nicknameText.setText("Non connecté");
                nicknameText.setEnabled(false);
                infoServeurLab.setText("");

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

  public void attendreUnMessage(Socket socketTransfert) throws IOException {

        myComm = new Communication(socketTransfert, this);

  }

  public synchronized void ajouterOnglet(String nickname) {
        if (!verifOngletExiste(nickname)) {
            myTabs.add(new OngletDeConversation(this));
            myTabs.lastElement().setName(nickname);
            conversationTabPane.add(myTabs.lastElement());
        } else {
            // on le met au premier plan
            int i = 0;
            for (; (i < myTabs.size()) && !myTabs.elementAt(i).getName().equals(nickname); i++) {
            }
            conversationTabPane.setSelectedIndex(i);

        }
  }

  public boolean verifConnecteExiste(String nickname) {
        int i = 0;
        for (; (i < connectes.size()) && !connectes.elementAt(i).equals(nickname); i++) {
        }
        return (i < connectes.size());
  }

  public boolean verifOngletExiste(String nickname) {
        int i = 0;
        for (; (i < myTabs.size()) && !myTabs.elementAt(i).getName().equals(nickname); i++) {
        }
        return (i < myTabs.size());
  }

  public int getOngletIndex(String nickname) {
        // -1 si l'onglet n'existe pas
        int i = 0;
        for (; (i < myTabs.size()) && !myTabs.elementAt(i).getName().equals(nickname); i++) {
        }
        return (i < myTabs.size()) ? i : -1;
  }

  public OngletDeConversation getOnglet(String nickname) {
        // -1 si l'onglet n'existe pas
        int i = 0;
        for (; (i < myTabs.size()) && !myTabs.elementAt(i).getName().equals(nickname); i++) {
        }

        if (i < myTabs.size()) {
            return myTabs.elementAt(i);
        } else {
            return null;
        }
  }

  public void suppOnglet(OngletDeConversation tab) {

        int i = 0;
        for (; (i < myTabs.size()) && !connectesList.getModel().getElementAt(i).toString().equals(tab.getName()); i++) {
        }
        connectesList.removeSelectionInterval(i, i + 1);
        myTabs.remove(getOngletIndex(tab.getName()));
        conversationTabPane.remove(tab);
  }

  public void selectItemList(String tabName) {
        int i = 0;
        for (; (i < myTabs.size()) && !connectesList.getModel().getElementAt(i).toString().equals(tabName); i++) {
        }
        connectesList.setSelectedIndex(i);
  }

  public void majListeConnectes(Message msg) {
        try {
            // vide la liste des connectés
            connectes.removeAllElements();

            String chaineListeConnectes = new String(msg.getContenu(), "UTF8");
            // on la split depuis la chaine (et grace aux sauts de ligne)
            String[] tabListeConnectes = chaineListeConnectes.split("\n");
            // on créé le liste d'items
            javax.swing.DefaultListModel dlm = new javax.swing.DefaultListModel();
            // on insère les nicknames
            for (int i = 0; i < tabListeConnectes.length; i++) {
                if (!tabListeConnectes[i].equals(nicknameUser)) {
                    dlm.addElement(tabListeConnectes[i]);
                    connectes.add(tabListeConnectes[i]);
                }
            }

            // on les affiche dans la liste
            connectesList.setModel(dlm);

        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(ClientView.class.getName()).log(Level.SEVERE, null, ex);
        }
  }

  public String nicknameActif() {
        if (conversationTabPane.getSelectedComponent() != null) {
            return conversationTabPane.getSelectedComponent().getName();
        } else {
            return "";
        }
  }

  public void ajouterMessageConversation(Message msg) {
        byte[] tabCont = new byte[msg.getContenu().length];
        tabCont = msg.getContenu();
        String contenu = new String(tabCont);
        GregorianCalendar dateCourante = new GregorianCalendar();
        dateCourante.setTime(new Date());

        // si l'onglet existe déjà (si on a déjà ouvert une conversation avec la personne)
        if (getOngletIndex(msg.getNickSource()) > -1) {
            myTabs.elementAt(getOngletIndex(msg.getNickSource())).addMessage(msg.getNickSource(), dateCourante, contenu, this);
        } else {
            // on cré l'onglet
            ajouterOnglet(msg.getNickSource());
            myTabs.elementAt(getOngletIndex(msg.getNickSource())).addMessage(msg.getNickSource(), dateCourante, contenu, this);

        }

        conversationTabPane.setForegroundAt(getOngletIndex(msg.getNickSource()), Color.red);

  }

  public void initEnvoyerFichier(OngletDeConversation myTab) {

        if(!verifConnecteExiste(myTab.getName()))
            myTab.addSysMessage("<html>Transfert impossible, <strong>"+ myTab.getName() + " n'est plus connecté.</strong></html>");
        else if (!droitEnvoyerFichierA(myTab.getName()))
            myTab.addSysMessage("<html>Transfert impossible, <strong>pas plus de 1 fichier</strong> par personne.</html>");
        else {
            JFileChooser parcourirBoite = new JFileChooser();
            int returnVal = parcourirBoite.showOpenDialog(this.getComponent());

            // si un fichier a été selectionné
            if (returnVal == 0) {
                File file = parcourirBoite.getSelectedFile();

                try {
                    // taille du fichier
                    int fileSize = (int) file.length();
                    // nombre de paquet determiné en fonction de la taille du fichier
                    int nbPaquets = (int) (fileSize / 100 + 1);

                    // entête pour prévenir le client du nom du fichier, de sa taille et du nombre de paquet
                    String enTeteFichier = new String(file.getAbsolutePath() + "\n" + file.getName() + "\n" + file.length() + "\n" + nbPaquets);
                    Message msg = new Message((byte) 15, nicknameUser, myTab.getName(), enTeteFichier.getBytes());

                    // on crée le flux en sortie
                    java.io.OutputStream out = socket.getOutputStream();
                    DataOutputStream fluxSortie = new DataOutputStream(out);

                    // on envoie l'entête
                    msg.send(fluxSortie);
                    getStatusMessageLabel().setText(new String("Attente de la réponse du client..."));

                    // on ajoute le transfert à la liste des transfert
                    transfertsEnCours.add(new EtatFichierTransfert(nicknameUser, msg.getNickDestination(), file.getAbsolutePath(), 0, nbPaquets, fileSize));

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

            }
        }
  }

  public void envoyerFichier(Message msg) {
        try {

            String enteteFichier = new String(msg.getContenu(), "UTF8");
            // on la split depuis la chaine (et grace aux sauts de ligne)
            String[] metaInfoFichier = enteteFichier.split("\n");
            threadUpload.add( new EnvoieFichier(this, getTransfertFromSource(msg.getNickDestination())) );
            getOnglet(msg.getNickSource()).addSysMessage("<html>Le client accepte le fichier: <strong>transfert en cours...</strong></html>");

        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(ClientView.class.getName()).log(Level.SEVERE, null, ex);
        }
  }

  public boolean droitEnvoyerFichierA(String dest) {
        return (getTransfertIndexFromDestinataire(dest) == -1);
  }

  public void demanderConfirmEnvoieFichier(Message msg) {

        OkCancelDialog prompt = new OkCancelDialog(this.getFrame(), true, msg.getNickSource() + " veut vous envoyer un fichier. Acceptez-vous ?");
        ClientApp.getApplication().show(prompt);

        try {
            java.io.OutputStream out = socket.getOutputStream();
            DataOutputStream sortie = new DataOutputStream(out);


            // le client accepte le transfert de fichier
            if (prompt.getReturnStatus() == 1) {



                JFileChooser parcourirBoite = new JFileChooser();
                parcourirBoite.setApproveButtonText("Enregistrer");
                parcourirBoite.setDialogTitle("Enregister dans le dossier...");
                parcourirBoite.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnVal = parcourirBoite.showOpenDialog(this.getComponent());


                // un emplacement pour le fichier a été choisi
                if (returnVal == 0) {

                    // dit à la source que le destinataire (nous) a tout accepté
                    Message myMsg = new Message((byte) 10, nicknameUser, msg.getNickSource(), msg.getContenu());
                    myMsg.send(sortie);

                    // ouvre un onglet
                    ajouterOnglet(msg.getNickSource());

                    if (getOnglet(msg.getNickSource()) != null) {
                        getOnglet(msg.getNickSource()).addSysMessage("<html>Un emplacement a été choisi: <strong>transfert en cours...</strong></html>");
                    }

                    // ---- on retient que la source doit nous envoyer un fichier
                    // on obtient le nom du fichier
                    String enteteFichier = new String(msg.getContenu(), "UTF8");
                    // on la split depuis la chaine (et grace aux sauts de ligne)
                    String[] metaInfoFichier = enteteFichier.split("\n");
                    String fichierPath = parcourirBoite.getSelectedFile().getAbsolutePath() + "/" + metaInfoFichier[1];

                    // on ajoute une entrée dans le tableau dédié
                    transfertsEnCours.add(new EtatFichierTransfert(msg.getNickSource(), nicknameUser, fichierPath, 0, Integer.parseInt(metaInfoFichier[3]), Integer.parseInt(metaInfoFichier[2])));

                    // on prépare le fichier
                    RandomAccessFile f = new RandomAccessFile(fichierPath, "rw");
                    f.setLength((long) Long.parseLong(metaInfoFichier[2]));

                } else {
                    // dit à la source que le destinataire (nous) a refusé
                    Message myMsg = new Message((byte) 11, nicknameUser, msg.getNickSource(), "");
                    myMsg.send(sortie);
                }

            } else {
                // dit à la source que le destinataire (nous) a refusé
                Message myMsg = new Message((byte) 11, nicknameUser, msg.getNickSource(), "");
                myMsg.send(sortie);
            }


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

  public int getTransfertIndexFromSource(String source) {
        // retourne -1 si non trouvé
        int i = 0;
        for (; (i < transfertsEnCours.size()) && !transfertsEnCours.elementAt(i).getSource().equals(source); i++) {
        }
        return (i < transfertsEnCours.size()) ? i : -1;
  }

  public int getTransfertIndexFromDestinataire(String dest) {
        // retourne -1 si non trouvé
        int i = 0;
        for (; (i < transfertsEnCours.size()) && !transfertsEnCours.elementAt(i).getDestinataire().equals(dest); i++) {
        }
        return (i < transfertsEnCours.size()) ? i : -1;
  }

  public EtatFichierTransfert getTransfertFromSource(String src) {
        // retourne -1 si non trouvé
        int i = 0;
        for (; (i < transfertsEnCours.size()) && !transfertsEnCours.elementAt(i).getSource().equals(src); i++) { }

        if(i < transfertsEnCours.size())
            return transfertsEnCours.elementAt(i);
        else
            return null;
  }

  public void ajouterPaquetAuFichier(Message msg) {

        try {

            int indexDownload = getTransfertIndexFromSource(msg.getNickSource());
            if(indexDownload != -1) {
                int nbPaquetsTransferes = transfertsEnCours.elementAt(indexDownload).getNbPaquetsTransferes();
                transfertsEnCours.elementAt(indexDownload).setNbPaquetsTransferes(nbPaquetsTransferes + 1);

                RandomAccessFile fichierOut = new RandomAccessFile(transfertsEnCours.elementAt(indexDownload).getFichierPath(), "rw");

                fichierOut.seek(transfertsEnCours.elementAt(indexDownload).getFichierPointeur());

                fichierOut.write(msg.getContenu());
                transfertsEnCours.elementAt(indexDownload).setFichierPointeur(fichierOut.getFilePointer());

                fichierOut.close();
                transfertView.refreshDownload();

            }

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

  public void annulerUpload(String dest) {
        // on dit au thread de s'arrêter
        for(EnvoieFichier t : threadUpload)
            if(t.getEft().getDestinataire().equals(dest))
                t.setRun(false);
  }

  public void finDownloadFichier(Message msg) {

        transfertView.addMessageDownload("<html><i>" + getTransfertFromSource(msg.getNickSource()).getFichierLocalPath() + "</i> terminé.</html>");

        if (getOnglet(msg.getNickSource()) != null)
            getOnglet(msg.getNickSource()).addSysMessage("<html><strong>Transfert terminé!</strong></html>");

        getTransfertFromSource(msg.getNickSource()).setNbPaquetsTransferes( getTransfertFromSource(msg.getNickSource()).getNbPaquetsTotal() );
        transfertView.refreshDownload();
       
        // on enlève le transfert de la liste
        suppTransfertSrc(msg.getNickSource());
        transfertView.refreshDownload();
  }

  public void refuseChangNickname() {
        statusMessageLabel.setText("Le pseudo n'a pas été changé. Un autre utilisateur utilise ce pseudo.");
        nicknameText.setText(nicknameUser);
        nicknameText.setEnabled(true);
  }

  public void accepteChangNickname() {
        statusMessageLabel.setText("Le pseudo a été changé !");
        nicknameUser = nicknameText.getText();
        nicknameText.setEnabled(true);

  }

  public void notifieChangementNickname(Message msg) {
        // stock l'ancien et le nouveau nickname dans un tableau depuis le contenu du message
        String[] nicks = new String(msg.getContenu()).split("\n");

        // met à jour la table des transferts
        // la source si elle existe
        if( getTransfertFromSource(nicks[0]) != null)
            getTransfertFromSource(nicks[0]).setSource(nicks[1]);
        // les destinataires
        for (EtatFichierTransfert t : transfertsEnCours)
            if(t.getDestinataire().equals(nicks[0]))
                t.setDestinataire(nicks[1]);

        // on force la mise à jours de la liste des dl et ul
        transfertView.getDownloadPanel().removeAll();
        transfertView.getUploadPanel().removeAll();
       
        // met à jours les onglets
        OngletDeConversation tab = getOnglet(nicks[0]);
        if (tab != null) {
            tab.addSysMessage("<html><strong>" + nicks[0] + "</strong> s'appelle désormais <strong>" + nicks[1] + "</strong></html>");
            conversationTabPane.setTitleAt(getOngletIndex(nicks[0]), nicks[1]);
            tab.setName(nicks[1]);
        }
  }

  public boolean activationBoutonEnvoyer() {
        // on active le bouton "Envoyer" pour autoriser l'envoie de message
        // il faut répondre à plusieurs conditions:
        // - être connecté au serveur
        // - avoir une conversation en cours (un onglet)
        // - le message ne soit pas vide

        if (!contenuMessage.getText().equals("") && socket.isConnected() && !nicknameActif().equals("")) {
            envoyerMessageButton.setEnabled(true);
            return true && verifConnecteExiste(nicknameActif());
        } else {
            envoyerMessageButton.setEnabled(false);
            return false;
        }
  }

  public void updateNickname() {
        // si le nickname a bien changé
        if (!nicknameText.getText().equals(nicknameUser)) {
            this.getFrame().requestFocus();
            if (socket.isConnected()) {
                try {
                    // on crée le flux en sortie
                    java.io.OutputStream out = socket.getOutputStream();
                    DataOutputStream sortie = new DataOutputStream(out);


                    // on bloque le champ d'edition
                    nicknameText.setEnabled(false);
                    statusMessageLabel.setText("Demande de changement de pseudo en cours...");

                    Message msg = new Message((byte) 3, nicknameUser);
                    msg.setContenu(nicknameText.getText());
                    // on envoit le message et la réponse du serveur déclenchera le reste..
                    msg.send(sortie);

                } catch (IOException ex) {
                    statusMessageLabel.setText("Le pseudo ne serra pas changé.");
                    nicknameText.setText(nicknameUser);
                    nicknameText.setEnabled(true);
                }
            }

        }
  }

  public void suppTransfertDest(String dest) {
        int n=-1, i=0;

        for (EtatFichierTransfert t : transfertsEnCours)
        {
            if(t.getDestinataire().equals(dest))
                n = i;
            i++;
        }

        if(n != -1) transfertsEnCours.remove(n);
  }

  public void suppTransfertSrc(String src) {
        int n=-1, i=0;

        for (EtatFichierTransfert t : transfertsEnCours)
        {
            if(t.getSource().equals(src))
                n = i;
            i++;
        }

        if(n != -1) transfertsEnCours.remove(n);
  }

  public void notifieSuppConnecte(String nick) {
        OngletDeConversation tab = getOnglet(nick);
        if(tab != null)
            tab.addSysMessage("<html><strong>"+ nick + "</strong> n'est plus connecté.</html>");
  }

  /**
   *  ---------------------------
   * METHODES privées
   * ---------------------------
   *  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.
   *
   *  <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
   */
  @SuppressWarnings("unchecked")
  private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        conversationTabPane = new javax.swing.JTabbedPane();
        lateralTabPane = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        connectesList = new javax.swing.JList();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        contenuMessage = new javax.swing.JTextArea();
        envoyerMessageButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        infoServeurLab = new javax.swing.JLabel();
        iconAvatarLab = new javax.swing.JLabel();
        nicknameText = new javax.swing.JTextField();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        confConnexionMenuItem = new javax.swing.JMenuItem();
        connexionMenuItem = new javax.swing.JMenuItem();
        deconnexionMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        voirTransfertsMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setMinimumSize(new java.awt.Dimension(0, 100));
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setOpaque(false);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(projetcs.ClientApp.class).getContext().getResourceMap(ClientView.class);
        conversationTabPane.setBackground(resourceMap.getColor("conversationTabPane.background")); // NOI18N
        conversationTabPane.setForeground(resourceMap.getColor("conversationTabPane.foreground")); // NOI18N
        conversationTabPane.setMinimumSize(new java.awt.Dimension(400, 150));
        conversationTabPane.setName("conversationTabPane"); // NOI18N

        lateralTabPane.setName("lateralTabPane"); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        connectesList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = {};
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        connectesList.setName("connectesList"); // NOI18N
        connectesList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                connectesListValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(connectesList);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
        );

        lateralTabPane.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N

        jPanel4.setName("jPanel4"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        contenuMessage.setColumns(20);
        contenuMessage.setRows(5);
        contenuMessage.setName("contenuMessage"); // NOI18N
        contenuMessage.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                contenuMessageFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                contenuMessageFocusLost(evt);
            }
        });
        contenuMessage.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                contenuMessageKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(contenuMessage);

        envoyerMessageButton.setMnemonic('e');
        envoyerMessageButton.setEnabled(false);
        envoyerMessageButton.setLabel(resourceMap.getString("envoyerMessageButton.label")); // NOI18N
        envoyerMessageButton.setName("envoyerMessageButton"); // NOI18N
        envoyerMessageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                envoyerMessageButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 521, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(envoyerMessageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
            .addComponent(envoyerMessageButton, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
        );

        jPanel1.setName("jPanel1"); // NOI18N

        infoServeurLab.setForeground(resourceMap.getColor("infoServeurLab.foreground")); // NOI18N
        infoServeurLab.setText(resourceMap.getString("infoServeurLab.text")); // NOI18N
        infoServeurLab.setName("infoServeurLab"); // NOI18N

        iconAvatarLab.setIcon(resourceMap.getIcon("iconAvatarLab.icon")); // NOI18N
        iconAvatarLab.setText(resourceMap.getString("iconAvatarLab.text")); // NOI18N
        iconAvatarLab.setName("iconAvatarLab"); // NOI18N

        nicknameText.setFont(resourceMap.getFont("nicknameText.font")); // NOI18N
        nicknameText.setText(resourceMap.getString("nicknameText.text")); // NOI18N
        nicknameText.setEnabled(false);
        nicknameText.setName("nicknameText"); // NOI18N
        nicknameText.setOpaque(false);
        nicknameText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                nicknameTextFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                nicknameTextFocusLost(evt);
            }
        });
        nicknameText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                nicknameTextKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(iconAvatarLab, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(infoServeurLab, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nicknameText, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(iconAvatarLab)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(nicknameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(infoServeurLab)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(conversationTabPane, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lateralTabPane, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(15, 15, 15))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(conversationTabPane, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE))
                    .addComponent(lateralTabPane, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setMnemonic('f');
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        confConnexionMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        confConnexionMenuItem.setText(resourceMap.getString("confConnexionMenuItem.text")); // NOI18N
        confConnexionMenuItem.setName("confConnexionMenuItem"); // NOI18N
        confConnexionMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confConnexionMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(confConnexionMenuItem);

        connexionMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        connexionMenuItem.setText(resourceMap.getString("connexionMenuItem.text")); // NOI18N
        connexionMenuItem.setName("connexionMenuItem"); // NOI18N
        connexionMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connexionMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(connexionMenuItem);

        deconnexionMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
        deconnexionMenuItem.setText(resourceMap.getString("deconnexionMenuItem.text")); // NOI18N
        deconnexionMenuItem.setEnabled(false);
        deconnexionMenuItem.setName("deconnexionMenuItem"); // NOI18N
        deconnexionMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deconnexionMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(deconnexionMenuItem);

        jSeparator1.setName("jSeparator1"); // NOI18N
        fileMenu.add(jSeparator1);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(projetcs.ClientApp.class).getContext().getActionMap(ClientView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        jMenu1.setMnemonic('r');
        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        voirTransfertsMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
        voirTransfertsMenuItem.setMnemonic('t');
        voirTransfertsMenuItem.setText(resourceMap.getString("voirTransfertsMenuItem.text")); // NOI18N
        voirTransfertsMenuItem.setName("voirTransfertsMenuItem"); // NOI18N
        voirTransfertsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                voirTransfertsMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(voirTransfertsMenuItem);

        menuBar.add(jMenu1);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 458, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
  }

  /**
   *  </editor-fold>//GEN-END:initComponents
   */
  private void confConnexionMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
                                                     
        ClientApp.getApplication().show(configConnectView);
  }

  /**
   * GEN-LAST:event_confConnexionMenuItemActionPerformed
   */
  private void connexionMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
                                                 
        connexion();
  }

  /**
   * GEN-LAST:event_connexionMenuItemActionPerformed
   */
  private void deconnexionMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
                                                   
        deconnexion();
  }

  /**
   * GEN-LAST:event_deconnexionMenuItemActionPerformed
   */
  private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
                                            
        deconnexion();
  }

  /**
   * GEN-LAST:event_exitMenuItemActionPerformed
   */
  private void contenuMessageKeyPressed(java.awt.event.KeyEvent evt) {
                                         
        activationBoutonEnvoyer();
  }

  /**
   * GEN-LAST:event_contenuMessageKeyPressed
   */
  private void contenuMessageFocusGained(java.awt.event.FocusEvent evt) {
                                          
        activationBoutonEnvoyer();
  }

  /**
   * GEN-LAST:event_contenuMessageFocusGained
   */
  private void contenuMessageFocusLost(java.awt.event.FocusEvent evt) {
                                        
        activationBoutonEnvoyer();
  }

  /**
   * GEN-LAST:event_contenuMessageFocusLost
   */
  private void envoyerMessageButtonActionPerformed(java.awt.event.ActionEvent evt) {
                                                    
        if (activationBoutonEnvoyer()) // si il y a bien un message a envoyer dans le textarea
        {
            try {
                // on crée le flux en sortie
                java.io.OutputStream out = socket.getOutputStream();
                DataOutputStream sortie = new DataOutputStream(out);

                // on créé on envoit le message
                Message msg = new Message((byte) 13, nicknameUser, nicknameActif(), contenuMessage.getText());
                msg.send(sortie);

                // on ajoute le message localement
                GregorianCalendar dateCourante = new GregorianCalendar();
                dateCourante.setTime(new Date());
                myTabs.elementAt(getOngletIndex(nicknameActif())).addMessage(nicknameUser, dateCourante, contenuMessage.getText(), this);

                // on vide le champi text
                contenuMessage.setText("");

            } catch (IOException ex) {
                statusMessageLabel.setText("Le message n'a pas été envoyé.");
            }
        }
  }

  /**
   * GEN-LAST:event_envoyerMessageButtonActionPerformed
   */
  private void nicknameTextFocusGained(java.awt.event.FocusEvent evt) {
                                        
        nicknameText.setOpaque(true);
        nicknameText.repaint();
  }

  /**
   * GEN-LAST:event_nicknameTextFocusGained
   */
  private void nicknameTextFocusLost(java.awt.event.FocusEvent evt) {
                                      
        nicknameText.setOpaque(false);
        nicknameText.repaint();
        updateNickname();
  }

  /**
   * GEN-LAST:event_nicknameTextFocusLost
   */
  private void nicknameTextKeyPressed(java.awt.event.KeyEvent evt) {
                                       
        // quand on appuis sur Enter
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
            infoServeurLab.requestFocus();
        }
  }

  /**
   * GEN-LAST:event_nicknameTextKeyPressed
   */
  private void connectesListValueChanged(javax.swing.event.ListSelectionEvent evt) {
                                          
        // récupère le Nickname de l'item cliqué
        if (connectesList.getSelectedValue() != null) {
            ajouterOnglet(connectesList.getSelectedValue().toString());
        }
  }

  /**
   * GEN-LAST:event_connectesListValueChanged
   */
  private void voirTransfertsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
                                                      
        transfertView.setVisible(true);
  }

  /**
   * GEN-LAST:event_voirTransfertsMenuItemActionPerformed
   *  ---------------------------
   * ATTRIBUTS privés
   * ---------------------------
   *  Variables declaration - do not modify//GEN-BEGIN:variables
   */
  private javax.swing.JMenuItem confConnexionMenuItem;

  private javax.swing.JList connectesList;

  private javax.swing.JMenuItem connexionMenuItem;

  private javax.swing.JTextArea contenuMessage;

  private javax.swing.JTabbedPane conversationTabPane;

  private javax.swing.JMenuItem deconnexionMenuItem;

  private javax.swing.JButton envoyerMessageButton;

  private javax.swing.JLabel iconAvatarLab;

  private javax.swing.JLabel infoServeurLab;

  private javax.swing.JMenu jMenu1;

  private javax.swing.JPanel jPanel1;

  private javax.swing.JPanel jPanel2;

  private javax.swing.JPanel jPanel4;

  private javax.swing.JScrollPane jScrollPane1;

  private javax.swing.JScrollPane jScrollPane2;

  private javax.swing.JPopupMenu.Separator jSeparator1;

  private javax.swing.JTabbedPane lateralTabPane;

  private javax.swing.JPanel mainPanel;

  private javax.swing.JMenuBar menuBar;

  private javax.swing.JTextField nicknameText;

  private javax.swing.JProgressBar progressBar;

  private javax.swing.JLabel statusAnimationLabel;

  private javax.swing.JLabel statusMessageLabel;

  private javax.swing.JPanel statusPanel;

  private javax.swing.JMenuItem voirTransfertsMenuItem;

  /**
   *  End of variables declaration//GEN-END:variables
   */
  private final Timer messageTimer;

  private final Timer busyIconTimer;

  private final Icon idleIcon;

  private final Icon[] busyIcons =  new Icon[15];

  private int busyIconIndex =  0;

  private JDialog aboutBox;

  private String adrServeur;

  private long portServeur;

  private String nicknameUser;

  private Socket socket;

  private Communication myComm;

  /**
   *  listes des onglets de conversation
   */
  private Vector<OngletDeConversation> myTabs =  new Vector<OngletDeConversation>();

  /**
   *  listes des transferts en cours
   */
  private Vector<EtatFichierTransfert> transfertsEnCours =  new Vector<EtatFichierTransfert>();

  /**
   *  liste des connectes
   */
  private Vector<String> connectes =  new Vector<String>();

  private Vector<EnvoieFichier> threadUpload =  new Vector<EnvoieFichier>();

  /**
   *  ---------------------------
   * FENETRES HOMEMADE
   * ---------------------------
   */
  private ConfigConnexionView configConnectView;

  private TransfertEnCoursView transfertView;

}
TOP

Related Classes of projetcs.ClientView

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.