(resolvido) Duvida de Como Passar dados entre Classes

3 respostas
jonasjgs2

bom dia a todos...

eu tenho um jframe "Principal" que fiz como exemplo
e neste jframe tem um campo jtextfield "que coloquei como public" e tem um botao...

quando eu clico no botao ele chama uma classe chamada tarefa,
a qual ira executar varias tarefas...

nesta classe tarefa eu tenho que setar os valores no campo do frame principal...
porem ele executa toda a classe tarefa mas no frame principal so aparece a ultima...
ou seja o frame principal fica congelado sem mostrar as outras mensagens
e so mostra a ultima porque a classe tarefa terminou de executar...

eu tenho um problema como esta no meu projeto principal...
e nao estou tendo uma ideia de como resolver

se alguem poder me ajudar eu agradeco...

segue a baixo as classes para analise de vcs...

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ValoresEntreTelas;

/**
 *
 * @author Admin
 */
public class Principal extends javax.swing.JFrame {

    /**
     * Creates new form Principal
     */
    public Principal() {
        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();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Confirma");
        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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(117, 117, 117)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(156, 156, 156)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(108, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(68, 68, 68)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(136, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Tarefa tarefa = new Tarefa(this);
    }

    /**
     * @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/tutorial/uiswing/lookandfeel/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(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.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 Principal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    public javax.swing.JTextField jTextField1;
    // End of variables declaration
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ValoresEntreTelas;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Admin
 */
public class Tarefa {

    private Principal principal;

    public  Tarefa(Principal principal) {
        this.principal = principal;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);
        }
        Tarefa01();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);
        }
        Tarefa02();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);
        }
        Tarefa03();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);
        }
        Tarefa04();
    }

    private void Tarefa01() {
        System.out.println("Tarefa 001");
        principal.jTextField1.setText("Tarefa 001");
    }

    private void Tarefa02() { 
        System.out.println("Tarefa 002");
        principal.jTextField1.setText("Tarefa 002");
    }

    private void Tarefa03() {
        System.out.println("Tarefa 003");
        principal.jTextField1.setText("Tarefa 003");
    }

    private void Tarefa04() {
        System.out.println("Tarefa 004");
        principal.jTextField1.setText("Tarefa 004");
    }
}

3 Respostas

douglaskd

bom dia jonas,

sua classe tarefa deve ser uma thread

jonasjgs2

bom dia dougas,
eu fiz uma thread tambem o problema
e que o form principal ele tem que ficar aguardando
o termino no processo:
entao eu criei transformei a tarefa em uma thead
e colocar uma variavel global nela para
eu consegui testar se terminou

e fiz um loop como mostrado abaixo para
checar se ela terminou
porem enquanto nao termina o while que coloquei
tambem fica preso e nao mostra...

o while abaixo eu fiz apos o evento do botao para executar a thead

Tarefa2 tarefa2 = new Tarefa2(this);
        tarefa2.start();
        while (tarefa2.fim==false) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
        
        this.jTextField1.setText("Terminou");
douglaskd

vamos fazer o seguinte:

sua classe Tarefa vai implementar Runnable.

coloque somente isso no Construtor:
public  Tarefa(Principal principal) {  
        this.principal = principal;  
}
sobrescreva o método run():
public void run() {
        try {  
            Thread.sleep(1000);  
        } catch (InterruptedException ex) {  
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);  
        }  
        Tarefa01();  
        try {  
            Thread.sleep(1000);  
        } catch (InterruptedException ex) {  
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);  
        }  
        Tarefa02();  
        try {  
            Thread.sleep(1000);  
        } catch (InterruptedException ex) {  
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);  
        }  
        Tarefa03();  
        try {  
            Thread.sleep(1000);  
        } catch (InterruptedException ex) {  
            Logger.getLogger(Tarefa.class.getName()).log(Level.SEVERE, null, ex);  
        }  
        Tarefa04();   
    
  }

no JFrame principal coloque os imports:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
e no botão para iniciar a tarefa coloque:
ExecutorService executor = Executors.newFixedThreadPool(10);
Runnable tarefa = new Tarefa(this);
executor.execute(tarefa);

//para de aceitar novas tarefas.
executor.shutdown();

// Aguarda tarefa ser finalizada, 
while (!executor.isTerminated()) {
//enquanto a tarefa nao terminar não faz nada
}

 //faz algo aqui quando a tarefa terminar

diga mais sobre como o programa deve funcionar pois ficou confuso.

Criado 27 de março de 2013
Ultima resposta 27 de mar. de 2013
Respostas 3
Participantes 2