Visualizzazione dei risultati da 1 a 7 su 7
  1. #1
    Utente di HTML.it
    Registrato dal
    Nov 2007
    Messaggi
    327

    Non riesco a passare un jTextArea ad un'altra classe

    Buon giorno ragazzi, sono al termine di un progetto dietro al quale sto da vari giorni, ho praticamente finito mi manca soltanto l'ultimo passo, ma credo sia veramente una cosa banale, potreste darmi una mano?
    Non riesco a passare una jTextArea (il Layout grafico l'ho creato tramite Netbeans) ad un'altra classe (la classe Server) di modo che questa possa stamparci su.


    Chat_v1c è la main class, poi ci sono NewJFrame, Server, Client.
    La main class è così composta:
    codice:
    package chat_v1c;
    import java.net.*;
    import java.io.*;
    
    public class Chat_v1c 
    {
        public static void main(String[] args) throws InterruptedException 
        {
            Server objS=new Server();
            objS.start();
            NewJFrame objG=new NewJFrame();
            objG.setVisible(true);
        }
    }
    Il mio intento è quello di passare alla classe Server la JTextArea presente all'interno di NewJFrame che è così composto

    codice:
    package chat_v1c;
    
    public class NewJFrame extends javax.swing.JFrame {
    
        /**
         * Creates new form NewJFrame
         */
        int i=0;
        
        
        Client objC=new Client();
        
        public NewJFrame() {
            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() {
    
            jButton1 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jButton1.setText("Send");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
    
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 380, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(0, 8, Short.MAX_VALUE))
                        .add(layout.createSequentialGroup()
                            .add(jTextField1)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jButton1)))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                    .add(18, 18, 18)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jButton1)
                            .add(61, 61, 61))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            if(i==0)
            {            
                //objS.pass(jTextArea1);
                objC.connectToSocket();
                objC.sendToServer(jTextField1.getText());
                i=i+1;   
            }
            else
            {
                objC.sendToServer(jTextField1.getText());
                
            }
            
        }                                        
    
        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        }                                           
    
       
        public static void main(String args[]) {
        
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
          
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
    }
    L'ideale sarebbe poter passare alla classe Server la JtextArea subito dopo che nel main faccio
    codice:
    objS.start();
    Tuttavia se dal main non fosse possibile (non ci riesco) andrebbe bene passarglielo anche dall'interno dell'interfaccia grafica, ma l'importante è che sia imediatamente appena si apre, senza la necessità di premere alcun pulsante e prima che gli altri pulsanti vengano premuti (anche qui non riesco).

    Ringrazio anticipatamente chiunque mi voglia aiutare.

  2. #2
    Passarla all'oggetto server sul metodo start è impossibile in quanto la jTextArea viene creata alla costruzione dell'oggetto NewJFrame.
    Quello che puoi fare è aggiungere un parametro al costruttore della classe NewJFrame in modo da potergli passare il tuo oggetto server in questo modo dall'interno del costruttore puoi tranquillamente passargli il tuo oggetto JTextArea dopo che questo è stato correttamente costruito.
    codice:
    public NewJFrame(Server server) {
            initComponents();
            //qui passo l'oggetto JTextArea al server
            server.setJTextArea(jTextArea1);
        }
    Ciao.

  3. #3
    Utente di HTML.it
    Registrato dal
    Nov 2007
    Messaggi
    327
    Originariamente inviato da francesco.muia
    Passarla all'oggetto server sul metodo start è impossibile in quanto la jTextArea viene creata alla costruzione dell'oggetto NewJFrame.
    Quello che puoi fare è aggiungere un parametro al costruttore della classe NewJFrame in modo da potergli passare il tuo oggetto server in questo modo dall'interno del costruttore puoi tranquillamente passargli il tuo oggetto JTextArea dopo che questo è stato correttamente costruito.
    codice:
    public NewJFrame(Server server) {
            initComponents();
            //qui passo l'oggetto JTextArea al server
            server.setJTextArea(jTextArea1);
        }
    Ciao.
    Grazie per la risposta
    Materialmente ho potuto provare soltanto adesso.
    Ho provato a fare come dici tu, dunque dal main ho passato l'oggetto objS in questo modo
    codice:
    public class Chat_v1c 
    {
        public static void main(String[] args) throws InterruptedException 
        {
            Server objS=new Server();
            objS.start();
            NewJFrame objG=new NewJFrame(objS);
            objG.setVisible(true);
        }
    }
    e nella classe NewJFrame in questo modo
    codice:
    public NewJFrame(Server server) {
            
            initComponents();
            server.passa(jTextArea1);
    
        }
    Così facendo però ottengo errore qui
    codice:
    java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            }
    in particolare Constructor NewJFrame in class chat_v1c.NewJFrame cannot be applied to given types.
    Sono riuscito a passarlo facendo così
    codice:
    public NewJFrame() {
            Server objS=new Server();
            initComponents();
            objS.passa(jTextArea1);
    
        }
    L'oggetto viene quindi passato, ma c'è sicuramente qualcosa che non va in quanto quando provo a stampare sulla jTextArea trovo un java.lang.NullPointerException mentre se stampo con il classico
    codice:
    System.out.println
    tutto va a buon fine.
    Non so più dove mettere le mani

  4. #4
    Allora il problema è dato dal fatto che tu hai due punti in cui crei l'oggetto NewJFrame, cosa che non è normale come mai invochi due volte la costruzione di questo frame ?

  5. #5
    Utente di HTML.it
    Registrato dal
    Nov 2007
    Messaggi
    327
    Se ti riferisci al codice presente all'interno di NewJFrame questo è codice autogenerato da Netbeans in seguito alla creazione di un'interfaccia grafica con gli appositi strumenti messi a disposizione.

    Attualmente compila e va tutto a buon fine con
    codice:
    public NewJFrame() {
            Server objS=new Server();
            initComponents();
            objS.passa(jTextArea1);
    }
    a runtime non appena nella classe Server si arriva al punto in cui c'è il comando
    codice:
    jTextArea.append("XXXX");
    mi segnala il java.lang.NullPointerException.


    Posto tutto il codice per completezza:
    codice:
    package chat_v1c;
    import java.net.*;
    import java.io.*;
    
    public class Chat_v1c 
    {
        public static void main(String[] args) throws InterruptedException 
        {
            Server objS=new Server();
            objS.start();
            NewJFrame objG=new NewJFrame();
            objG.setVisible(true);
        }
    }
    codice:
    package chat_v1c;
    import java.net.*;
    import java.io.*;
    public class Server extends Thread
    {
        BufferedReader dalClient;
        PrintWriter alClient;
        javax.swing.JTextArea jTextArea;
        
        
        
        public void passa(javax.swing.JTextArea a)
        {
            this.jTextArea=a;
            
        }
        
        public Server(){}
    
    
        @Override
        public void run()
        {
            String text="";
            Socket clientSocket=null;
            ServerSocket serverSocket=null;
            try
            {
                serverSocket=new ServerSocket(5555);
                clientSocket = serverSocket.accept();
                dalClient=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                alClient = new PrintWriter(clientSocket.getOutputStream(), true);
                while(!text.equals("bye"))
                {
                    text=dalClient.readLine();
                    System.out.println("ECCOMI!");
                    System.out.println(clientSocket.getInetAddress() + "Said: " + text + "\n");
                    jTextArea.append(clientSocket.getInetAddress() + "Said: " + text + "\n");
                }
                alClient.print(clientSocket.getInetAddress()+ "Disconnected!");
                serverSocket.close();
                System.out.println("FFFUORII");
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    codice:
    package chat_v1c;
    import java.net.*;
    import java.io.*;
    
    public class Client 
    {
        
        Socket s1;
        PrintWriter alServer;
        BufferedReader dalServer;
        String text;
        //BufferedReader t = new BufferedReader(new InputStreamReader(System.in));
    
        
        
        public void connectToSocket()
        {
            
            try
            {
            
            s1 = new Socket ("169.254.100.208",5555);
            System.out.print("Connection with "+s1.getInetAddress()+" establised! \n");
            alServer= new PrintWriter(s1.getOutputStream(),true);
            dalServer = new BufferedReader(new InputStreamReader(s1.getInputStream()));
            }
            catch(IOException e)
            {
                System.out.println(e);
            }
        }
        
        
        
        
        public void sendToServer(String text)
        {
            
               this.text=text;
                    
                    alServer.println(text); 
        }
    }
    codice:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package chat_v1c;
    
    /**
     *
     * @author fabrizio
     */
    public class NewJFrame extends javax.swing.JFrame {
    
        /**
         * Creates new form NewJFrame
         */
        int i=0;
        
        
        Client objC=new Client();
        
        
        public NewJFrame() {
            Server objS=new Server();
            initComponents();
            objS.passa(jTextArea1);
    
        }
    
        /**
         * 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() {
    
            jButton1 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jButton1.setText("Send");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
    
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 380, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(0, 8, Short.MAX_VALUE))
                        .add(layout.createSequentialGroup()
                            .add(jTextField1)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jButton1)))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                    .add(18, 18, 18)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jButton1)
                            .add(61, 61, 61))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            if(i==0)
            {            
                //objS.pass(jTextArea1);
                objC.connectToSocket();
                objC.sendToServer(jTextField1.getText());
                i=i+1;   
            }
            else
            {
                objC.sendToServer(jTextField1.getText());
                
            }
            
        }                                        
    
        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                           
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /*
             * Set the Nimbus look and feel
             */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with the
             * default look and feel. For details see
             * http://download.oracle.com/javase/tu...feel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                   
    }

  6. #6
    Utente di HTML.it
    Registrato dal
    Nov 2007
    Messaggi
    327
    Oppure un altro metodo potrebbe essere quello di cambiare il main in questo modo, che dite?
    In questo modo quando parte start() della classe server la JtextArea è già presente in quella classe.
    Il problema è che non so mettere mano al codice generato da Netbeans e quindi non so come creare e dove andare a mettere la funzione prendi jTextArea
    codice:
    public class Chat_v1c 
    {
        public static void main(String[] args) throws InterruptedException 
        {
            Server objS=new Server();
            NewJFrame objG=new NewJFrame();
            objG.setVisible(true);
            objG.prendijTextArea();
            objS.passajTextArea();
            objS.start();
        }
    }

  7. #7
    Utente di HTML.it
    Registrato dal
    Nov 2007
    Messaggi
    327
    Niente proprio non riesco a venirne a capo...
    La visualizzazione del testo nella jTextArea è l'ultimo passo che mi manca per l'ultimazione di questa chat nessuno proprio riesce ad aiutarmi?

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.