Swing , pq os resultados só apareçem quando a função termina ?!

Olá galera, esse é meu primeiro post da comunidade e queria antes de tudo parabenizar VCs pelo site, que é “muito bom”, varios tutoriais/artigos legais, forum bem organizado… blz…

Bem, partindo para a minha dúvida:
Estou com um pequeno problema, estava criando um programas pra listar as maquinas da rede e a medida que fossem verificadas seria pra colocar elas numa lista… mas a lista só aparece despois que o evento/metodo de Listar acaba !

Depois de horas batendo cabeça, tentando descobrir o problema (que pensava ser de lógica) percebi que era com a “classe” Swing, pois usei um componente da AWT e funcionou perfeitamete.

Abaixo fiz um exemplo das duas funcionando em “paralelo” na AWT vai aparecendo , mas na swing só no final… :frowning:
Como posso contornar esse problema ?!

public class TesteSwing extends javax.swing.JFrame {
   
   /** Creates new form TesteSwing */
   public TesteSwing() {
      initComponents();
   }
                          
   private void initComponents() {
      jScrollPane1 = new javax.swing.JScrollPane();
      jTextArea1 = new javax.swing.JTextArea();
      jLabel1 = new javax.swing.JLabel();
      textArea1 = new java.awt.TextArea();
      jLabel2 = new javax.swing.JLabel();
      jProgressBar1 = new javax.swing.JProgressBar();
      jButton1 = new javax.swing.JButton();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      jTextArea1.setColumns(20);
      jTextArea1.setRows(5);
      jScrollPane1.setViewportView(jTextArea1);

      jLabel1.setText("Swing:");

      jLabel2.setText("AWT");

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

      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(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
               .addGroup(layout.createSequentialGroup()
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                     .addComponent(jLabel1))
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(jLabel2)
                     .addComponent(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)))
               .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
            .addContainerGap())
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addGap(6, 6, 6)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(jLabel1)
               .addComponent(jLabel2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
               .addComponent(textArea1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
            .addGap(14, 14, 14)
            .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );
      pack();
   }// </editor-fold>                        

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      try {
         for (int i = 0; i &lt= 100; i += 5) {
            Thread.sleep(50);
            textArea1.append("linha " + i + "\n");
            jTextArea1.append("linha " + i + "\n");
            jProgressBar1.setValue(i);
         }
      } catch (InterruptedException ex) {
         ex.printStackTrace();
      }
   }                                        
   
   /**
    * @param args the command line arguments
    */
   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            new TesteSwing().setVisible(true);
         }
      });
   }
   
   // Declaração de variáveis - não modifique                     
   private javax.swing.JButton jButton1;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JLabel jLabel2;
   private javax.swing.JProgressBar jProgressBar1;
   private javax.swing.JScrollPane jScrollPane1;
   private javax.swing.JTextArea jTextArea1;
   private java.awt.TextArea textArea1;
   // Fim da declaração de variáveis                   
   
}

Bem, como estou "iniciando" em JAVA , queria saber qual a melhor lib para a interface gráfica, testei a Swing e a SWT(eclipse) . e gostei mais da SWT, mas como gosto mais do Editor Visual do NetBeans (muito mais prático) … fico meio sem saber …
Ou se tiver alguma forma de usar a SWT como a Swing no EditorVisual do Netbeans, por favor me digam como ?!?

vlwwwww !!

Por que quando seu programa executa a Thread atual do programa fica tão ocupado que não consegue atualizar a tela ao mesmo tempo para resolver isto , você pode utilizar um Listener , ou uma Thread que no caso seria uma boa utilizar SwingWorker para está tarefa.

Espero ter contribuido com você.

Com esse tempo tb, nem que vc quisesse… sõa 50ms!!!É muito rápido…
Se vc quer que cada item do for vá aparecendo, nunca que vc conseguiria ver…

Pode ser uma boa mesmo…

O swing trabalha com uma thread soh que executa os eventos. Portanto, qdo voce executa um evento, ele chama essa thread e o desenho da tela soh vai ser executada quando a thread terminar.

Como o pessoal já falou, vc pode usar SwingWork, ou vc pode estartar o evento em uma thread diferente, ou então se quiser ir mais a fundo usa um observer. Aqui no guj mesmo tem um tutorial legal.

Ahhh… eu imageni que tivesse alguma coisa com os eventos !!!
esse Java é engraçado… hehe :smiley:
Blz… vou dar uma estudada nesses assuntos que me indicaram…
vlw…

Como posso criar umas mascara para formatar IPs com as seguintes condições:
Só sumeros de 0…254
Podendo ter diferentes “layouts” tipo:
10.0.0.1
192.168.0.1
200.123.23.123
etc…

Tentei usar umas maskara ###.###.###.###, mas não ta dando certo…

Da uma olhada em expressões regulares

alguem sabe onde tem um material de SwingWorker em portugues de preferencia ?!!? :lol:
vlw !!