0

Estoy programando un chat de grupo en Java, tengo una clase para definir la interfaz gráfica del cliente y otra para la interfaz gráfica del servidor. Además, los protocolos de comunicación de cliente y servidor están en otras 2 clases (ClientTest y ServerTest).

Quiero que los mensajes que envía el servidor no solo se vean en la salida estándar sino también en un JTextArea que he definido en la interfaz del cliente, sin embargo el editor me dice que no conoce ese textField textServer, aún habiendolo declarado public y estar todas las clases en un mismo repertorio.

También he intentado crear un metodo public void setTextServer() en la clase de la interfaz cliente, que luego uso en la clase ServerTest y me dice lo mismo, que no conoce este método.

3
  • 3
    Dos cosas, primero, si alguien edita tu pregunta, procura no quitar lo que editaron pues lo hicieron para que tu pregunta sea más clara. No fui yo quien lo editó, pero estoy seguro que quien lo hizo lo hizo con la mejor intención de ayudarte. Segunda, postea tu código para que te podamos ayudar más fácilmente. Según lo que entiendo, lo que necesitas es que la clase donde está tu objeto que quieres editar tengo un método de acceso, un set, para poder poner los datos que quieras.
    – skw
    Commented el 19 abr. 2017 a las 11:44
  • Creo que sería bueno si compartes tu código (mínimo declaración de las clases, los campos/métodos en cuestión y donde y en que contexto se instan tus objetos). Sin eso es nada fácil de imaginarse tu arquitectura y encontrar donde no te permite el acceso que buscas. Commented el 19 abr. 2017 a las 20:46
  • Ademas de haber cambiado el textField a public tambien tenias que haberlo cambiado a static. Asi me funciono cuando quise modificar el textField de un formulario desde otra clase.
    – Alex
    Commented el 6 feb. 2020 a las 4:33

2 respuestas 2

0

JFrame cliente

  public class Cliente extends javax.swing.JFrame {
 //obtenemos la referencia del objeto servidor para modificar el textArea 
 del servidor desde el cliente    
 private Servidor servidor;
 /**
 * Creates new form Cliente
 */
 public Cliente(Servidor s) {
    super("CLIENTE");
    initComponents();
    this.servidor = s;
}

public void setServidor(Servidor servidor) {
    this.servidor = servidor;
}


/**
 * Metodo usado para que desde el servidor se modifique el textArea desde el 
   cliente
 * @param texto 
 */
public void modificar(String texto){
    txtMensajesCliente.append(texto+"\n");


}

el actionPerformed para modificar el texto

private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    txtMensajesCliente.append("CLIENTE: "+txtMensajeCliente.getText());
    servidor.modificar("CLIENTE :"+txtMensajeCliente.getText());


}       

JFrame servidor

private Cliente cliente;
/**
 * Creates new form Servidor
 */
public Servidor(Cliente cliente) {
    super("SERVIDOR");
    initComponents();
    this.cliente=cliente;
}

private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {                                          

    txtMensajesServidor.append("SERVIDOR: "+txtMensajeServidor.getText()+"\n");
    cliente.modificar("SERVIDOR: "+txtMensajeServidor.getText());

}                                         

/**
 * Metodo usado para que desde el cliente se modifique el textArea del servidor
 * @param texto 
 */
public void modificar(String texto){
    txtMensajesServidor.append(texto+"\n");

}

Clase Main

 public static void main(String[] args) {


    Cliente cliente = new Cliente(null);
    cliente.setVisible(true);
    Servidor servidor = new Servidor(cliente);
    servidor.setVisible(true);
    cliente.setServidor(servidor);



}
2
  • esta muy largo pero algo es algo :) Commented el 20 abr. 2017 a las 2:23
  • Me he inspirado de tu idea de hacer que la clase Cliente herede de una JFrame y así ponerlo todo junto (metodos para manipular el cliente y la interfaz gráfica de este) te dejo el código si le quieres echar un vistazo!
    – Daniel Gdx
    Commented el 21 abr. 2017 a las 9:17
0

clase Cliente

public class Client extends javax.swing.JFrame{

private Socket client = null;
private String hostName;
private int port;
private BufferedReader entree;
private PrintWriter sortie;
private javax.swing.JButton boutonQuiter;
private javax.swing.JButton boutonConnexion;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel6;
private java.awt.Label label4;
private java.awt.Label label5;
private java.awt.TextArea textClient;
private java.awt.TextArea textServer;
private java.awt.TextField textField2;  //adresse IP du server où on veut se connecter
private java.awt.TextField textField4;  //port pour la communication
/** Le constructeur qui indique sur quel serveur se connecter et quel port solliciter
* il prend plus de paramètre, il s'initialise en prennant les infos fournies
* sur l'interface directement
* @throws IOException si erreur de connexion
*/
public Client() throws IOException {
initComponents();
    setTimer();
    setVisible(true);
    setTitle("Client");   
}

private void setTimer(){            //méthode pour afficher l'heure
    javax.swing.Timer labelTimer;
    DateFormat formatData=DateFormat.getTimeInstance(DateFormat.MEDIUM);
    labelTimer=new Timer(1000,new ActionListener(){
        public void actionPerformed(ActionEvent e){
            jLabel1.setText(formatData.format(new Date()));
        }
    });
    labelTimer.start();        
}
/**
 * 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(); //horloge
    jLabel2 = new javax.swing.JLabel(); //label Client
    jLabel3 = new javax.swing.JLabel(); //label Port
    textField2 = new java.awt.TextField();
    textField4 = new java.awt.TextField();
    jPanel2 = new javax.swing.JPanel();
    boutonQuiter = new javax.swing.JButton();
    boutonConnexion = new javax.swing.JButton();
    jPanel3 = new javax.swing.JPanel();
    textClient = new java.awt.TextArea();    
    textServer = new java.awt.TextArea();
    label4 = new java.awt.Label();
    label5 = new java.awt.Label();
    jPanel6 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel2.setText("Client");

    jLabel3.setText("Port");

    textField2.setText("localhost");

    textField4.setText("2222");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(35, 35, 35)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel2)
                .addComponent(jLabel3))
            .addGap(117, 117, 117)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(textField2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGap(37, 37, 37))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap(22, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel2)
                .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(31, 31, 31)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jLabel3)
                .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    );

    boutonQuiter.setText("QUITTER");
    boutonQuiter.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            boutonQuiterMouseClicked(evt);
        }
    });

    boutonConnexion.setText("CONNEXION");
    boutonConnexion.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            try {
                boutonConnexionMouseClicked(evt);
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });


    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(50, 50, 50)
            .addComponent(boutonQuiter)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(boutonConnexion)
            .addGap(60, 60, 60))
    );
    jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(boutonQuiter)
                .addComponent(boutonConnexion))
            .addContainerGap())
    );

    label4.setText("Client");

    label5.setText("Serveur");

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addComponent(textClient, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 300, Short.MAX_VALUE)
            .addComponent(textServer, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addGap(61, 61, 61)
            .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(64, 64, 64))
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(textServer, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                .addComponent(textClient, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
            .addContainerGap())
    );

    jLabel1.setText("HELLO");

    javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
    jPanel6.setLayout(jPanel6Layout);
    jPanel6Layout.setHorizontalGroup(
        jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel6Layout.createSequentialGroup()
            .addGap(173, 173, 173)
            .addComponent(jLabel1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jPanel6Layout.setVerticalGroup(
        jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel6Layout.createSequentialGroup()
            .addComponent(jLabel1)
            .addGap(0, 12, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jPanel6, javax.swing.GroupLayout.Alignment.TRAILING, 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()
            .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(4, 4, 4)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    pack();
}// </editor-fold>                        
//bouton affiche Connexion si y a pas de client, sinon si client exite il affiche envoyer
private void boutonConnexionMouseClicked(java.awt.event.MouseEvent evt) throws IOException{                                      
  if(client==null){  
    try {
// Convertir la chaine de caractères "hostName" en une adresse IP valide du serveur
        hostName=textField2.getText(); //on récupère l'@ spécifiée
        port=Integer.parseInt(textField4.getText());
        InetAddress adresseIP = InetAddress.getByName(hostName);
//creer le Socket vers le serveur
        client = new Socket(adresseIP, port);
        appendServer("Nouveau client= "+client);
//on fixe un timeOut
        client.setSoTimeout(1000);// 1s
}
catch(UnknownHostException e){
        System.err.println("Je ne connais pas le serveur: "+hostName);
        appendServer("Je ne connais pas le serveur: "+hostName);
        throw e;
}
catch(SocketException e){
        System.err.println("erreur de connexion ou timeout");
        appendServer("erreur de connexion ou timeout");
        throw e;
}
    catch (IOException e) {
        System.err.println("Probleme de connexion sur:"+hostName);
        appendServer("Probleme de connexion sur:"+hostName);
        throw e;
}
System.out.println("Connexion OK sur "+hostName);
    appendServer("Connexion OK sur "+hostName);

try {
        entree = new BufferedReader(new InputStreamReader(client.getInputStream() ) );
        sortie = new PrintWriter(client.getOutputStream() );
}
catch (IOException e) {
        System.err.println("PB creation des streams");
        appendServer("PB creation des streams");
        System.exit(1);
    }
    boutonConnexion.setText("ENVOYER");

  }
}                                 

/**
 *
 * @return socket client
 */
public Socket getSocket(){
return client;
}

/**
 *
 * @param chaine :message du serveur à ajouter au textServer
 */
public void appendServer(String chaine){
    textServer.append(chaine+"\n");
}

/** lit les caracteres envoyés par le serveur.
* @return un objet String qui contient l'ensemble des caractères lus
*/
public String lireServeur(){
String ligne=null;
try{
        ligne = entree.readLine();
}
catch (IOException e) {
        System.err.println("rien a lire");
}
return ligne;
}

/** Envoie des données au serveur.
* @param ligne les caractères à envoyer
*/
public void ecrireServeur(String ligne){
sortie.println(ligne);
sortie.flush();
}

/** teste la connexion.
*@return un booléen notifiant l'état de la connexion
*/
public boolean estConnect(){
    return client.isConnected();
}

/** Fermeture du socket.
*/
public void fermer(){
    try{
        entree.close();
        sortie.close();
        if (client != null){
    client.close();
    System.out.println ("Fermeture ok");
        }
}
catch(IOException e){
        System.err.println("Erreur à la fermeture des flux!");
}
}

/**Appel de la methode fermer()
 */
@Override
protected void finalize(){
fermer();
}

public void communiquer() {
// Que dit le serveur ?
    String ligne = lireServeur();
System.out.println("Serveur : "+ligne);
    appendServer("Serveur : "+ligne);
//Requete au serveur a partir de la console
System.out.print("Entree : ");

BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String entree;
try{
        while ((entree = console.readLine()) != null) {
    ecrireServeur(entree);
    ligne = lireServeur();
    if (ligne != null) {
                System.out.println("Serveur : "+ligne);// pour voir
                if (ligne.equals("Au revoir"))
        break;
    }
    System.out.print("Entree : ");  
        }
        console.close();
}
catch(IOException e){
        System.err.println("Erreur de lecture console");
}
}

}

Clase ClienteTest

public class MonClientTest{

    Client  mc=null; //initialisation de la variable locale
    try{
                mc = new Client();
                System.out.println("mc = "+mc+ "client:"+mc.getSocket());

    }
    catch(IOException e) {
        System.err.println("erreur de realisation du client"+mc);
        if (mc != null){
            mc.fermer();
            mc = null; //on perd l'objet
        }
    }

    if (mc != null) {
        mc.communiquer();
        mc.fermer();

    }
    else
        System.err.println("Impossible de créer le client, mc ==null !!");
}

}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.