Partage
  • Partager sur Facebook
  • Partager sur Twitter

Probleme affichage jTextArea

Sujet résolu
    23 octobre 2008 à 2:33:20

    Bonjour, tout d'abord félicitations pour vos tuto, ce sont vraiment les meilleur que l'on trouve!
    Voila j'ai un problème en java.
    Je voudrais faire un petit programme pour afficher le titre d'une page web en entrant son url dans un jTextField.
    J'utilise la classe SwingWorker pour instancier un thread par recherche (et par conséquent pouvoir lancer plusieurs recherches simultanément).
    J'ai donc 2 classes, la première héritant de JFrame, et la deuxième héritant de SwingWorker.
    Je voudrais afficher le titre de la page directement à partir de la classe SwingWorker mais je n'y arrive pas.
    Savez-vous comment faire ?
    Mon code :


    Classe NewJFrame :
    public class NewJFrame extends javax.swing.JFrame {
            
        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() {
    
            jTextField1 = new javax.swing.JTextField();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jButton1 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jTextField1.setText("http://");
            jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jTextField1MouseClicked(evt);
                }
            });
    
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
    
            jButton1.setText("Fetch");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jLabel1.setText("Number of actives workers :");
    
            jLabel2.setText("0");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton1))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(26, 26, 26)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addContainerGap(12, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        @SuppressWarnings("static-access")
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            MySwingWorker SW = new MySwingWorker();
            SW.adress = jTextField1.getText();
            SW.execute();
    }                                        
        
        
    private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {
        jTextField1.setText("http://");
    }
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    NewJFrame window = new NewJFrame();
                    window.setVisible(true);
                    window.setLocationRelativeTo(null);
    
                }
            });
        }
    
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
    
    }
    






    Classe MySwingWorker :
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import javax.swing.SwingWorker;
    
    
    
    public class MySwingWorker extends SwingWorker<String, String>{
        public String adress = new String();
        public String title = new String();
    
        @Override
        @SuppressWarnings("static-access")
        protected String doInBackground() throws InterruptedException {
            
    
        try {
                
                Thread.currentThread().sleep(5000);
                URL url = new URL(adress);                                        
                URLConnection conn=url.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                
                
                String line = new String();
                String one = "<title>";
                String two = "</title>";
                int begin = -1;
                int end;
    
                while((line=br.readLine()) !=null){
                    
                    begin = line.indexOf(one);
                    end = line.lastIndexOf(two);
                    if(begin!=-1){
                        this.title = line.substring(begin+7, end);
                    }
                }
            }
        catch (IOException ex) {
            }
            return title;
        }
    
    
    }
    


    Merci d'avance :)
    • Partager sur Facebook
    • Partager sur Twitter
      23 octobre 2008 à 8:53:03

      Voici tes classes un peu modifiée et ce que j'ai obtenu :

      Classe : NewJFrame

      package Test;
      
      public class NewJFrame extends javax.swing.JFrame {
              
          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() {
      
              jTextField1 = new javax.swing.JTextField();
              jScrollPane1 = new javax.swing.JScrollPane();
              jTextArea1 = new javax.swing.JTextArea();
              jButton1 = new javax.swing.JButton();
              jLabel1 = new javax.swing.JLabel();
              jLabel2 = new javax.swing.JLabel();
      
              setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      
              jTextField1.setText("http://");
              jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
                  public void mouseClicked(java.awt.event.MouseEvent evt) {
                      jTextField1MouseClicked(evt);
                  }
              });
      
              jTextArea1.setColumns(20);
              jTextArea1.setRows(5);
              jScrollPane1.setViewportView(jTextArea1);
      
              jButton1.setText("Fetch");
              jButton1.addActionListener(new java.awt.event.ActionListener() {
                  public void actionPerformed(java.awt.event.ActionEvent evt) {
                      jButton1ActionPerformed(evt);
                  }
              });
      
              jLabel1.setText("Number of actives workers :");
      
              jLabel2.setText("0");
      
              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
              getContentPane().setLayout(layout);
              layout.setHorizontalGroup(
                  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addGroup(layout.createSequentialGroup()
                      .addContainerGap()
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                              .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
                              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                              .addComponent(jButton1))
                          .addGroup(layout.createSequentialGroup()
                              .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                              .addGap(26, 26, 26)
                              .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                      .addContainerGap())
              );
              layout.setVerticalGroup(
                  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                  .addGroup(layout.createSequentialGroup()
                      .addContainerGap()
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                          .addComponent(jButton1)
                          .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                      .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addGap(18, 18, 18)
                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                          .addComponent(jLabel1)
                          .addComponent(jLabel2))
                      .addContainerGap(12, Short.MAX_VALUE))
              );
      
              pack();
          }// </editor-fold>
      
          @SuppressWarnings("static-access")
      private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
              MySwingWorker SW = new MySwingWorker(this);
              SW.adress = jTextField1.getText();
              SW.execute();
      }                                        
          
      //Méthode d'écriture dans ta zone de texte
      public void setTextInField(String str){
      	//Celle-ci pour une seule ligne à la fois
      	//this.jTextArea1.setText(str);
      	this.jTextArea1.setText(this.jTextArea1.getText() + "\n" + str);
      }
          
      private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {
          jTextField1.setText("http://");
      }
      
          /**
          * @param args the command line arguments
          */
          public static void main(String args[]) {
              java.awt.EventQueue.invokeLater(new Runnable() {
                  public void run() {
                      NewJFrame window = new NewJFrame();
                      window.setVisible(true);
                      window.setLocationRelativeTo(null);
      
                  }
              });
          }
      
          // Variables declaration - do not modify
          private javax.swing.JButton jButton1;
          private javax.swing.JLabel jLabel1;
          private javax.swing.JLabel jLabel2;
          private javax.swing.JScrollPane jScrollPane1;
          private javax.swing.JTextArea jTextArea1;
          private javax.swing.JTextField jTextField1;
          // End of variables declaration
      
      }
      


      classe MySwingWorker :

      package Test;
      
      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.net.URL;
      import java.net.URLConnection;
      
      import javax.swing.SwingWorker;
      
      
      
      public class MySwingWorker extends SwingWorker<String, String>{
          public String adress = new String();
          public String title = new String();
          private NewJFrame nJFrame;
          
          //On passe une référence de ta fenêtre à cet objet 
          public MySwingWorker(NewJFrame frame){
          	this.nJFrame = frame;
          }
      
          protected String doInBackground() throws InterruptedException {
              
          try {
                 // Thread.currentThread().sleep(1000);
                  URL url = new URL(adress);                                        
                  URLConnection conn=url.openConnection();
                  BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                  
                  
                  String line = new String();
                  String one = "<title>";
                  String two = "</title>";
                  int begin = -1;
                  int end;
      
                  while((line=br.readLine()) !=null){
                      begin = line.indexOf(one);
                      end = line.lastIndexOf(two);
                      if(begin!=-1){
                          this.title = line.substring(begin+7, end);
                          //On écrit le titre avec la méthode de la classe 
                          this.nJFrame.setTextInField(this.title);
                      }
                  }
              }
          	catch (IOException ex) {
          		ex.printStackTrace();
          	}
          	return title;
          }
      
      
      }
      


      Résultat :

      Image utilisateur

      • Partager sur Facebook
      • Partager sur Twitter
        23 octobre 2008 à 11:40:41

        Merci beaucoup c'est exactement ça qu'il me fallait ! :)
        • Partager sur Facebook
        • Partager sur Twitter
          23 octobre 2008 à 11:47:39

          De rien... ;)
          Et penses au tag "Résolu"...

          Sinon, si tu veux pouvoir utiliser indépendamment tes deux objets, jette un oeil du côté du pattern Observer !
          • Partager sur Facebook
          • Partager sur Twitter

          Probleme affichage jTextArea

          × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
          × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
          • Editeur
          • Markdown