Problema com JTextField [Resolvido]

13 respostas
aldineireis

Galera como vai? estou precisando de uma mãozinha, desculpe se essa duvida não deveria estar postada aqui, mas eu postei no java basico e não consegui resolver, ja passei por varios topicos e nada. é o sequinte, tenho dois frames, um frame (Protocolo) possui varios campos, possuo um outro frame com um Jtable que possui um envento que quando clicado ele pega os dados da tabela e passa para o um metodo ( setaMatfun) dentro do frame Protocolo. até ai tudo bem, o problema é que os jtextfields não estão atualizado o texto, aqui vai o codigo.

//Evento da tabela

 private void tabelaprofMouseClicked(java.awt.event.MouseEvent evt) {                                        
     
    String m =((String) tabelaprof.getValueAt(tabelaprof.getSelectedRow(), 0));
    String n= ((String) tabelaprof.getValueAt(tabelaprof.getSelectedRow(), 1));
    Protocolo p = new Protocolo();
    p.setaMatfun(m, n);

  
   this.dispose();
      
    }
//metodo que seta os valores para os filds

 public   void setaMatfun(String m, String n){
 
       this.fildmatricula.setText(m);
       this.fildprof.setText(n);
    
   System.out.println("Teste: "+fildmatricula.getText().toString());
   System.out.println("Teste: "+fildprof.getText().toString());

    }
no console a saida é normal.

o que estou fazendo de errado?

obrigado a todos

13 Respostas

viniciusfaleiro

Tentou criar um contrutor de protocolo (String label1, String label2)?

Dai vc já define o valor dos campos na instanciação deles… JTextField t = new JTextField(label1);

Veja se funfa e fala ai…

aldineireis

Cara não deu, a minha interface protocolo possui um botão que chama a inteface da tabela ai eu seleciono na tabela e ele passa os dados para o fildmatricula, e fildprof atraves do evento acima, mas fica em branco os campos na interface.

viniciusfaleiro

Coloca todo o código ai q ta dificil de entender

aldineireis

fiz um exemplo menor e coloquei abaixo

eliangela

não estou conseguindo rodar seu código aqui porque está faltando muitas classes. Mas deixa eu falar algo mesmo assim:

não faça isso:
public   void setaMatfun(String m, String n){  
       
         JFormattedTextField matricula =  new JFormattedTextField(m);  
         JTextField prof = new JTextField(n);  
         fildmatricula = matricula;  
         fildprof = prof;  
           
         System.out.println("Teste: "+fildmatricula.getText().toString());  
         System.out.println("Teste: "+fildprof.getText().toString());  
   
     }
faça isso:
public   void setaMatfun(String m, String n){  
         fildmatricula.setText(m);  //alterei aqui
         fildprof.setText(n);   //alterei aqui
           
         System.out.println("Teste: "+fildmatricula.getText().toString());  
         System.out.println("Teste: "+fildprof.getText().toString());  
   
     }

Como não consegui rodar seu código aqui e não entendi muito bem o que vc quer, acredito que seja esse o problema, rsrrs

Até

aldineireis

obrigado por tentar ajudar mas eu ja tinha feito desse jeito, ai depois fiz do jeito que ta ai agora só pra testar, mesmo assim num deu.

eliangela

diga, qual é seu problema? vc está pedindo para alterar o texto do JTextField e o texto não está alterando?

aldineireis

bom deixo eu tentar explicar pra você, nesse frame protocolo tem um botão que abre uma outra tela (Profissionais tabela) que tem esse metodo

String m =((String) tabelaprof.getValueAt(tabelaprof.getSelectedRow(), 0));
    String n= ((String) tabelaprof.getValueAt(tabelaprof.getSelectedRow(), 1));
    Protocolo p = new Protocolo();
    p.setaMatfun(m, n);
   
  
   this.dispose();

esse metodo pega os dados que estão na linha selecionada da tabela e passa para as variaveis desse metodo que se encontra no frame protocolo:

public  void setaMatfun(String m, String n){
    
    
       fildmatricula.setText(m);
       fildprof.setText(n);
         
  
   System.out.println("Teste: "+fildmatricula.getText().toString());
   System.out.println("Teste: "+fildprof.getText().toString());

    }
deveria acontecer no frame(protocolo) "que ja se encontrava aberta o Frame" os filds: fildmatricula e fildprof aparecer o valor das variaveis m,n. e não acontece isso.
eliangela

vc está pegando o valor certo na tabela… ainda não consegui ver um motivo pra não funcionar…

Talvez se vc mandasse o código todo, daria pra rodar aqui e tentar ver o erro que tá dando.

até mais

eliangela

acabei de ver onde está o problema:
se o Frame protocolo já está aberto, vc tem que pegar os dados do frame aberto e não instanciar outro frame:

Protocolo p = new Protocolo();
p.setaMatfun(m, n);

como vc está instanciando outro objeto Protocolo, eu imagino que os campos estejam vazios, ao invés de vc pegar do que está aberto.

aldineireis

eliangela não consegui ainda fiz um exemplo simples pra vc rodar ai pra ver o que desejo:
sem imports pra ficar mais facil.

//protocolo
package Interface;

/**
 *
 * @author Aldinei
 */
public class Protocolo2 extends javax.swing.JFrame {

    /** Creates new form Protocolo2 */
    public Protocolo2() {
        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() {

        jLabel1 = new javax.swing.JLabel();
        fildmatricula = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        fildprof = new javax.swing.JTextField();
        btpesquisa = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Matricula::");

        jLabel2.setText("Profissional");

        fildprof.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fildprofActionPerformed(evt);
            }
        });

        btpesquisa.setText("pesquisa");
        btpesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btpesquisaActionPerformed(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()
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fildmatricula, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(fildprof, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btpesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .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.BASELINE)
                    .addComponent(fildmatricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fildprof, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btpesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(55, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>
public  void setaMatfun(String m, String n){

    
       fildmatricula.setText(m);
       fildprof.setText(n);


   System.out.println("Teste: "+fildmatricula.getText().toString());
   System.out.println("Teste: "+fildprof.getText().toString());

    }

    private void fildprofActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void btpesquisaActionPerformed(java.awt.event.ActionEvent evt) {
       tabelapro tabela = new tabelapro();
       tabela.setVisible(true);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Protocolo2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btpesquisa;
    private javax.swing.JTextField fildmatricula;
    private javax.swing.JTextField fildprof;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration

}

e a tabela

package Interface;

/**
 *
 * @author Aldinei
 */
public class tabelapro extends javax.swing.JFrame {

    /** Creates new form tabelapro */
    public tabelapro() {
        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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tabelapro = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tabelapro.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"00123", "Fulano de Tal "},
                {"00124", "Jose"}
            },
            new String [] {
                "Matricula", "Profissional"
            }
        ));
        tabelapro.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaproMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelapro);

        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()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(63, 63, 63))
        );

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

    private void tabelaproMouseClicked(java.awt.event.MouseEvent evt) {
     String m =((String) tabelapro.getValueAt(tabelapro.getSelectedRow(), 0));
    String n= ((String) tabelapro.getValueAt(tabelapro.getSelectedRow(), 1));
    Protocolo2 p = new Protocolo2();
    p.setaMatfun(m, n);

  
   this.dispose();

}

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new tabelapro().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabelapro;
    // End of variables declaration

}

por gentileza da uma olhada e me diz o que tenho que fazer.
obrigado

eliangela
Realmente foi como eu te disse no post passado: vc não pode fazer isso:
String m =((String) tabelaprof.getValueAt(tabelaprof.getSelectedRow(), 0));
String n= ((String) tabelaprof.getValueAt(tabelaprof.getSelectedRow(), 1));
Protocolo p = new Protocolo(); //ISSO ESTÁ ERRADO
p.setaMatfun(m, n);
this.dispose();
porque vc já está com uma Instância do Protocolo na memória. Quando vc faz Protocolo p = new Protocolo(); vc está criando uma nova instância e está atribuindo os valores para o Protocolo p, ao invés de atribuir os valores para o que já está aberto. resolvi fazendo isso: na sua classe tabelapro, eu alterei o construtor:
private Protocolo2 framePai; //esse é o frame Protocolo que está aberto

    public tabelapro(Protocolo2 framePai) {
        this.framePai = framePai; //passando ele por parâmetro
        initComponents();
    }
para que eu pudesse invocar os métodos do Protocolo que está na memória, desse jeito:
private void tabelaproMouseClicked(java.awt.event.MouseEvent evt) {
        String m = ((String) tabelapro.getValueAt(tabelapro.getSelectedRow(), 0));
        String n = ((String) tabelapro.getValueAt(tabelapro.getSelectedRow(), 1));
        framePai.setaMatfun(m, n); //agora sim estou acessando o método do Protocolo que está aberto, aquele que foi passado por parâmetro lá em cima
        this.dispose();
    }
... Apaguei o método main(String[] args) da sua classe protocolo2 e alterei a chamada da classe tabelapro, assim:
private void btpesquisaActionPerformed(java.awt.event.ActionEvent evt) {
        tabelapro tabela = new tabelapro(this);
        tabela.setVisible(true);
    }

Espero ter ajudado.
Qualquer dúvida, pode perguntar.

Até mais

aldineireis

Agradeço a você eliangela por me ajudar a resolver esse problema, muito obrigado, funcionou blz aqui.

Criado 19 de novembro de 2009
Ultima resposta 20 de nov. de 2009
Respostas 13
Participantes 3