JFrame abre e Fecha imediatamente

12 respostas
S

Olá amigos

tenho um frame de cadastro de clientes que num tderminado momento chama outro frame, acontece que o frame secnudário não fica ativo, ele fecha logo. Segue o codigo:

frame principal.

stmt = bd.ConexaoBancoDados.conexao().createStatement();               
           nomecliente = jTextField2.getText();          
           if (macao.equals("I")) {
              JFrame TrabBancoEJTable =  new TrabBancoEJTable();
              TrabBancoEJTable.setVisible(true); 
              TrabBancoEJTable.dispose(); 
           }

frame secundário.

/*
 * TrabBancoEJTable.java
 *
 * Created on 19 de Agosto de 2008, 09:57
 */

package assistenciadesktop;

import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.sql.*;
import java.util.*;
import assistenciadesktop.Listaclientes;
import bd.ConexaoBancoDados;

/**
 *
 * @author  silvio
 */
public class TrabBancoEJTable extends javax.swing.JFrame {

    private JTable jTable = null;
    private java.sql.Statement stmt;
   
    
    /** Creates new form TrabBancoEJTable */
    public TrabBancoEJTable()  throws HeadlessException, ClassNotFoundException {
        initialize();
    }
 
    public TrabBancoEJTable(GraphicsConfiguration gc) throws ClassNotFoundException {
        super();
        initialize();        
    }
    
    public TrabBancoEJTable(String title) throws HeadlessException, ClassNotFoundException {
        super();
        initialize();        
    }
    
    public TrabBancoEJTable(String title, GraphicsConfiguration gc) throws ClassNotFoundException {
        super(title,gc);
        initialize();
    }
    
    private Vector getProximaLinha(ResultSet rs, ResultSetMetaData rsmd)
            throws SQLException{
        Vector linhaAtual = new Vector();
        
        for (int i=1; i<=rsmd.getColumnCount() ; i++)
             linhaAtual.addElement(rs.getString(i));
        
        return linhaAtual; 
    }
    
    private void mostrarResultados(ResultSet rs) throws SQLException {
        boolean dados = rs.next();
        if (!dados ) {
            JOptionPane.showMessageDialog(this, "Nehum registro encontrado");
            return; 
        }
        Vector colunas = new Vector();
        Vector linhas = new Vector();
        
        try {
           ResultSetMetaData rsmd = rs.getMetaData();
           
           for (int i=1 ; i<=rsmd.getColumnCount(); i++) 
              colunas .addElement(rsmd.getColumnName(i));
           
           do {
               linhas.addElement(getProximaLinha(rs, rsmd));
           } while (rs.next());
          
           jTable = new JTable(linhas, colunas);
           JScrollPane jScrollPane = new JScrollPane(jTable);
           getContentPane().add(jScrollPane,java.awt.BorderLayout.CENTER);
           validate();       
        }    
         catch ( SQLException sqlex) {sqlex.printStackTrace(); }      
            
} 
    
    private void getJTable() throws ClassNotFoundException{
       Statement statement;
       ResultSet result;
       
       try {
           stmt = bd.ConexaoBancoDados.conexao().createStatement(); 
           String query = "select id,nome,telefone from clientes where upper(nome) ilike "+"upper('%"+
                         Listaclientes.nomecliente+"%') order by nome";
           ResultSet rs = stmt.executeQuery(query);
           mostrarResultados(rs);
           stmt.close();
       }
       catch (SQLException sqlex) {sqlex.printStackTrace();}
           
}
    
   
    
    /** 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() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

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

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new TrabBancoEJTable().setVisible(true);
                } catch (HeadlessException ex) {
                    Logger.getLogger(TrabBancoEJTable.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(TrabBancoEJTable.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

  
    private void initialize() throws ClassNotFoundException {
        
        this.setLocationRelativeTo(null);
        getJTable();
        this.setSize(400,300);
        this.setTitle("Clientes");
        //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }
    
    // Variables declaration - do not modify                     
    // End of variables declaration                   

}

se alguém puder ajudar?

Muito obrigado

Silvio Guedes

12 Respostas

FabricioPJ

tente trocar isso:

stmt = bd.ConexaoBancoDados.conexao().createStatement(); nomecliente = jTextField2.getText(); if (macao.equals("I")) { JFrame TrabBancoEJTable = new TrabBancoEJTable(); TrabBancoEJTable.setVisible(true); TrabBancoEJTable.dispose(); }

Por isso:

stmt = bd.ConexaoBancoDados.conexao().createStatement(); nomecliente = jTextField2.getText(); if (macao.equals("I")) { JFrame TrabBancoEJTable = new JFrame(); TrabBancoEJTable.setVisible(true); TrabBancoEJTable.dispose(); }

S

Olá amigo

stmt = bd.ConexaoBancoDados.conexao().createStatement();                   
    nomecliente = jTextField2.getText();              
    if (macao.equals("I")) {    
       JFrame TrabBancoEJTable =  new JFrame();      <--------- aqui
       TrabBancoEJTable.setVisible(true);     
       TrabBancoEJTable.dispose();     
    }

desta forma ele nem mostra o frame, e continua passando direto.

eu gostaria que o frame secundário permanecesse aberto até que eu fechasse o mesmo.

Silvio Guedes

Fernando_Generoso_da

silviogs:
Olá amigos

tenho um frame de cadastro de clientes que num tderminado momento chama outro frame, acontece que o frame secnudário não fica ativo, ele fecha logo. Segue o codigo:

frame principal.

stmt = bd.ConexaoBancoDados.conexao().createStatement();               
           nomecliente = jTextField2.getText();          
           if (macao.equals("I")) {
              JFrame TrabBancoEJTable =  new TrabBancoEJTable();
              TrabBancoEJTable.setVisible(true); 
              TrabBancoEJTable.dispose(); 
           }

frame secundário.

/*
 * TrabBancoEJTable.java
 *
 * Created on 19 de Agosto de 2008, 09:57
 */

package assistenciadesktop;

import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.sql.*;
import java.util.*;
import assistenciadesktop.Listaclientes;
import bd.ConexaoBancoDados;

/**
 *
 * @author  silvio
 */
public class TrabBancoEJTable extends javax.swing.JFrame {

    private JTable jTable = null;
    private java.sql.Statement stmt;
   
    
    /** Creates new form TrabBancoEJTable */
    public TrabBancoEJTable()  throws HeadlessException, ClassNotFoundException {
        initialize();
    }
 
    public TrabBancoEJTable(GraphicsConfiguration gc) throws ClassNotFoundException {
        super();
        initialize();        
    }
    
    public TrabBancoEJTable(String title) throws HeadlessException, ClassNotFoundException {
        super();
        initialize();        
    }
    
    public TrabBancoEJTable(String title, GraphicsConfiguration gc) throws ClassNotFoundException {
        super(title,gc);
        initialize();
    }
    
    private Vector getProximaLinha(ResultSet rs, ResultSetMetaData rsmd)
            throws SQLException{
        Vector linhaAtual = new Vector();
        
        for (int i=1; i<=rsmd.getColumnCount() ; i++)
             linhaAtual.addElement(rs.getString(i));
        
        return linhaAtual; 
    }
    
    private void mostrarResultados(ResultSet rs) throws SQLException {
        boolean dados = rs.next();
        if (!dados ) {
            JOptionPane.showMessageDialog(this, "Nehum registro encontrado");
            return; 
        }
        Vector colunas = new Vector();
        Vector linhas = new Vector();
        
        try {
           ResultSetMetaData rsmd = rs.getMetaData();
           
           for (int i=1 ; i<=rsmd.getColumnCount(); i++) 
              colunas .addElement(rsmd.getColumnName(i));
           
           do {
               linhas.addElement(getProximaLinha(rs, rsmd));
           } while (rs.next());
          
           jTable = new JTable(linhas, colunas);
           JScrollPane jScrollPane = new JScrollPane(jTable);
           getContentPane().add(jScrollPane,java.awt.BorderLayout.CENTER);
           validate();       
        }    
         catch ( SQLException sqlex) {sqlex.printStackTrace(); }      
            
} 
    
    private void getJTable() throws ClassNotFoundException{
       Statement statement;
       ResultSet result;
       
       try {
           stmt = bd.ConexaoBancoDados.conexao().createStatement(); 
           String query = "select id,nome,telefone from clientes where upper(nome) ilike "+"upper('%"+
                         Listaclientes.nomecliente+"%') order by nome";
           ResultSet rs = stmt.executeQuery(query);
           mostrarResultados(rs);
           stmt.close();
       }
       catch (SQLException sqlex) {sqlex.printStackTrace();}
           
}
    
   
    
    /** 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() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

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

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new TrabBancoEJTable().setVisible(true);
                } catch (HeadlessException ex) {
                    Logger.getLogger(TrabBancoEJTable.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(TrabBancoEJTable.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

  
    private void initialize() throws ClassNotFoundException {
        
        this.setLocationRelativeTo(null);
        getJTable();
        this.setSize(400,300);
        this.setTitle("Clientes");
        //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }
    
    // Variables declaration - do not modify                     
    // End of variables declaration                   

}

se alguém puder ajudar?

Muito obrigado

Silvio Guedes

Retire essa linha que irá funcionar:

TrabBancoEJTable.dispose();

att

Fernando Rosa

FabricioPJ

Opa… é verdade.

O frame.dispose() fecha o seu frame, matando seu processo.

dedspr

Pelo que eu entendi o erro esta aqui....

# TrabBancoEJTable.setVisible(true);   
#    TrabBancoEJTable.dispose();

Não pode dar um dispose...
ai você mandou o frame abrir e ao mesmo tempo fechar...

R

e dá um debug nisso rapaz.
Você iria achar o erro na hora :wink:

S

Olá amigos

segue código completo:

if (macao.equals("I")) {
              JFrame TrabBancoEJTable =  new TrabBancoEJTable(); <---- desta forma mostra o frame
              JFrame TrabBancoEJTable =  new JFrame();                    <---- assim não mostra
              TrabBancoEJTable.show(); 

           }   

           if  ( macao.equals("I")) {
              query = "insert into clientes ("+    
                      "codigo,"+         
                      "nome,"+           
                      "fantasia,"+       
                      "rg_inscestadual,"+
                      "cnpf_cnpj,"+      
                      "datanascimento,"+ 
                      "endereco,"+       
                      "cep,"+            
                      "cidade,"+         
                      "telefone,"+       
                      "telcomercial,"+   
                      "celular,"+        
                      "complemento,"+    
                      "email,"+          
                      "homepage,"+       
                      "contato,"+        
                      "cargo_contato,"+  
                      "css," +
                      "tipocliente,"+
                      "uf) values (" +
                      "'"+jTextField1.getText() +"',"+
                      "'"+jTextField2.getText() +"',"+
                      "'"+jTextField3.getText() +"',"+
                      "'"+jTextField4.getText() +"',"+
                      "'"+jTextField5.getText() +"',"+
                      "'"+jTextField6.getText() +"',"+
                      "'"+jTextField7.getText() +"',"+
                      "'"+jTextField8.getText() +"',"+
                      "'"+jTextField9.getText() +"',"+
                      "'"+jTextField10.getText()+"',"+
                      "'"+jTextField11.getText()+"',"+            
                      "'"+jTextField12.getText()+"',"+
                      "'"+jTextField13.getText()+"',"+
                      "'"+jTextField14.getText()+"',"+
                      "'"+jTextField15.getText()+"',"+
                      "'"+jTextField16.getText()+"',"+
                      "'"+jTextField17.getText()+"',"+
                      "'"+jTextField18.getText()+"',"+
                      "'"+(jComboBox1.getSelectedItem().toString()).substring(0,1)+"',"+
                      "'"+jComboBox2.getSelectedItem().toString()+"')";
              int result = stmt.executeUpdate( query );
                          
              if ( result == 1 ) {
                 JOptionPane.showMessageDialog(null, "Cliente incluido com sucesso." , "Aviso", JOptionPane.PLAIN_MESSAGE );
                 audita.setTxt("Usuário: " + FPrincipal.musuario + " Incluiu cliente"+jTextField1.getText()+", "+jTextField2.getText());               
                 audita.incluiAuditoria();
                 macao = "A";                 
                 stmt.close();
                 stmt = bd.ConexaoBancoDados.conexao().createStatement(); 
                 ResultSet rs = stmt.executeQuery("select * from clientes where codigo='" + jTextField1.getText() + "'"+
                         "and nome='"+jTextField2.getText()+"'");
                 rs.next(); 
                 id = rs.getObject(1);
                 stmt.close();
                 jTable1.removeAll();
                 CarregaLista();           
                 jTabbedPane1.setSelectedIndex(1);
              }     
              else {
                 JOptionPane.showMessageDialog(null, "Falha na inclusão!" , "Aviso", JOptionPane.WARNING_MESSAGE );
              }  
           }

mesmo assim ela passa para efetuar o teste do if seguinte.

muito obrigado

Silvio Guedes

Fernando_Generoso_da

Amigo,

JFrame TrabBancoEJTable = new JFrame(); <-Desta forma, irá aparecer um frame vazio, pois a instancia é apenas um JFrame, e não o frame que tu fez.

JFrame TrabBancoEJTable = new TrabBancoEJTable(); <–Desta forma, irá aparecer o frame TrabBancoEJTable, pois é ele quem você instancia, mas irá ser chamado na tua classe, apenas os métodos que foram sobrescritos da classe pai, no caso, JFrame.

Melhor seria fazer:

TrabBancoEJTable TrabBancoEJTable = new TrabBancoEJTable()

S

Olá amigo

testei o que você informou, mas funcionou da mesma forma que fiz. O problema é o seguinte:

ao chamar o frame na rotina:

nomecliente = jTextField2.getText();          
           if (macao.equals("I")) {
               TrabBancoEJTable TrabBancoEJTable = new TrabBancoEJTable(); 
               TrabBancoEJTable.show();                          
           } 
           if  ( macao.equals("I")) {
          .....

ele mostra o frame ao menos em branco, mas logo em seguida a execução o programa passa para o if seguinte, o programa não deveria ficar no frame chamado até que eu feche o mesmo.

muito obrigado

Silvio Guedes

Fernando_Generoso_da
if (macao.equals("I")) {   
     TrabBancoEJTable TrabBancoEJTable = new TrabBancoEJTable();   
     TrabBancoEJTable.show();                             
}   
if  ( macao.equals("I")) {

Pelo que está aqui, ele vai entrar nos dois if’s, isso pq tu compara o macao sempre com “I”. modifica o teu IF, e se é para entrar em apenas uma condição, utilize if/else if/else.

Raff

Ta precisando disso!

S

Olá amigo

agradeço de coração, à todos que me ajudaram. E falando em “Quanto há Ta precisando disso!” realmente preciso me certificar aliás , todos que procuram se especializar precisam disso.

Voltando ao assunto sem mais delongas. rsrsrsrsrsrsr.

Coloquei um jTextField e Button e faço a consulta ante de efetuar um novo cadastro:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO add your handling code here:
    nomecliente = jText_Procura.getText();          
    TrabBancoEJTable TrabBancoEJTable;
    try {
        TrabBancoEJTable = new TrabBancoEJTable();
        TrabBancoEJTable.setVisible(true);
    } catch (HeadlessException ex) {
        Logger.getLogger(Listaclientes.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Listaclientes.class.getName()).log(Level.SEVERE, null, ex);
    }
}

desta forma a tela fica aguardando algum evento, enquanto se localiza o cliente desejado.

Muito obrigado .

Silvio Guedes

Criado 21 de agosto de 2008
Ultima resposta 21 de ago. de 2008
Respostas 12
Participantes 6