2

Tenho uma aplicação onde em um JFrame eu crio novos registros para tabela mysql, e em um outro eu retorno um select numa JTable com todos os registros criados.

Tenho um botão alterar, que quando seleciono uma linha do JTable e clico nele, abre uma instancia do primeiro JFrame para criar registros, já setando as informações da linha selecionada.

Eu consigo atualizar, aparece o JoptionPane informando que foi atualizado, só que a aplicação também executa o código de inserção, criando assim um novo registro. O problema é que não consigo desvincular os actionListener do botão, então ele executa primeiramente o código de atualizar e depois de inserir.

Código do botão para criar registros:

public class teste3 extends javax.swing.JFrame {

    JButton jbutton;
    public teste3() {
        initComponents();

        this.jbutton = jButton1;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        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()
                .addGap(154, 154, 154)
                .addComponent(jButton1)
                .addContainerGap(173, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(121, 121, 121)
                .addComponent(jButton1)
                .addContainerGap(156, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JOptionPane.showMessageDialog(this, "oi");
    }                                        

    /**
     * @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(teste3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(teste3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(teste3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(teste3.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 teste3().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

código para atualizar:

public class Teste2 extends javax.swing.JFrame {

    teste3 teste3 = new teste3();

    public Teste2() {
        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() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        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()
                .addGap(154, 154, 154)
                .addComponent(jButton1)
                .addContainerGap(173, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(128, 128, 128)
                .addComponent(jButton1)
                .addContainerGap(148, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        teste3 teste3 = new teste3();
        teste3.setVisible(true);

        teste3.jbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                JOptionPane.showMessageDialog(teste3, "oi2");
            }
        });
    }                                        

    /**
     * @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(Teste2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Teste2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Teste2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Teste2.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 Teste2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}
4
  • Sem um Exemplo Mínimo, Completo e Verificável fica dificil ajudar. Você nao é novo no site, e eu sempre peço um mcve e vc ignora, como espera ajuda de alguem se nem voce mesmo ajuda a gente a te ajudar?
    – user28595
    10/06/2018 às 13:36
  • @Articuno, acho que agora consegui explicar melhor o meu problema. As ações dos dois botões são realizadas. Quero que apenas uma seja realizada. 11/06/2018 às 18:19
  • Ta vendo? Foi tao dificil assim criar um Exemplo Mínimo, Completo e Verificável? Vou tentar reproduzir o codigo para ver se localizo o erro.
    – user28595
    11/06/2018 às 18:37
  • Você chegou a ler minha resposta? Por que, por coincidencia, eu já citei qual o erro e como corrigir.
    – user28595
    11/06/2018 às 19:02

1 Resposta 1

2

O exemplo adicionado só reforça o que eu já havia mencionado, de que o causador do problema é você aplicar um listener dentro de outro listener. Neste trecho da classe Teste2:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    teste3 teste3 = new teste3();
    teste3.setVisible(true);

    teste3.jbutton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            JOptionPane.showMessageDialog(teste3, "oi2");
        }
    });
}  

Você inicia a outra tela e ao mesmo tempo, adiciona um novo listener ao botao desta nova tela.

Aqui há dois erros: um eu já mencionei, que é adicionar listener dentro de outro sem nenhum tipo de controle, e o outro erro é a violação de encapsulamento. Se não souber o que é isso, recomendo que leia esta resposta daqui mesmo do site para entender melhor.

O que ocorre, na verdade, não é a execução duas vezes do mesmo método, e sim a execução dos dois listeners que você aplica ao botão, pois na classe teste3 você já havia adicionado um listener.

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

...

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    JOptionPane.showMessageDialog(this, "oi");
}  

Como corrigir? Simples! Cada janela deve ser responsável por seus componentes e pelos eventos que dentro dela ocorrem, então basta separar a responsabilidade de cada janela dentro da classe própria e não ficar alterando componente de uma janela na outra, como eu ja mencionei, isso viola encapsulamento e é uma péssima pratica de programação, quando se faz sem ter noção do que isso signifique ou das consequências que isso pode causar.

Se jbutton1 pertence a classe teste3, deixe tudo que for evento somente nesta classe, e aplique apenas um ActionListner, pois dificilmente você precisará aplicar mais de um listener do mesmo tipo ao mesmo componente, particularmente nunca vi esse tipo de necessidade.

Sugiro que sempre inicie pelos tutoriais do java, e também há a tag aqui no site com muito conteúdo, pois se você quer mexer com a api swing mas sequer tem noção de como ela funciona, você vai enfrentar esse tipo de dificuldade e continuar fazendo esse tipo de implementação prejudicial a sua aplicação.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .