Duvida botao para abrir um frame e fechar o antigo

2 respostas
E

Bom Pessoal

Tenho uma aplicação bem simples que ao gerar um evento em um botão o programa abre um novo frame como faço pra ele abrir o novo frame e fechar o frame antigo sendo que ele o frame principal se eu fecha lo manualmente ele encerra o programa.Segue abaixo todo o código do frame que aciona o botão ou seja tela01.

Agradeço antecipadamente e aguardo respostas.

public class tela01 extends javax.swing.JFrame {

public tela01() {
    initComponents();
}

              
private void initComponents() {

    jButton1 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();

    jButton1.setText("jButton1");

    jLabel1.setText("Programa tela 01");

    jTextField1.setText("Programa de Cadastro ");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton2.setText("Cadastrar Clientes");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jLabel2.setText("Programa de Cadastro");

    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()
                    .addContainerGap()
                    .addComponent(jButton2))
                .addGroup(layout.createSequentialGroup()
                    .addGap(160, 160, 160)
                    .addComponent(jLabel2)))
            .addContainerGap(132, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(20, 20, 20)
            .addComponent(jLabel2)
            .addGap(28, 28, 28)
            .addComponent(jButton2)
            .addContainerGap(215, Short.MAX_VALUE))
    );

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

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    
    tela02 proxima = new tela02();
    proxima.setVisible(true);
    
    
}                                        

/**
 * @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(tela01.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(tela01.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(tela01.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(tela01.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 tela01().setVisible(true);
             
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
// End of variables declaration

}

2 Respostas

Henrique_Moraes

Ola amigo, para fechar o frame antigo, sem fechar todo o programa, esta propriedade deve ficar assim:

setDefaultCloseOperation(javax.swing.WindowConstants.HIDE);

E você está usando assim :

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

e para abrir o novo frame e fechar o antigo, você vai fazer assim :

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

this.dispose();
tela02 proxima = new tela02(); 
proxima.setVisible(true); 


}
E

Funcionou o método dispose(); Mas quando fui mudar o outro método para HIDE deu erro como segue abaixo ai logo depois eu retirei toda esta linha de código e funcionou normal como segue abaixo favor explicar o que aconteceu.Obrigado a todos.

setDefaultCloseOperation(javax.swing.WindowConstants.HIDE);

// setDefaultCloseOperation(javax.swing.WindowConstants.HIDE);

Criado 15 de novembro de 2012
Ultima resposta 15 de nov. de 2012
Respostas 2
Participantes 2