Fix Jbutton that is running 2 events

Asked

Viewed 96 times

2

I have an application where in a Jframe I create new records for mysql table, and in another I return a select JTable with all records created.

I have a change button, which when I select a Jtable line and click on it, opens an instance of the first Jframe to create records, already setting the information of the selected line.

I can update, Joptionpane appears stating that it has been updated, but the application also executes the insertion code, thus creating a new record. The problem is that I can’t unlink the actionListener from the button, so it first executes the update code and after inserting.

Code of the button to create records:

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                   
}

code to update:

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                   
}
  • Without a [mcve] It’s hard to help. You are not new to the site, and I always ask for a mcve and you ignore, as you expect help from someone if even you help us to help you?

  • @Articuno, I think I have now managed to explain my problem better. The actions of the two buttons are performed. I want only one to be performed.

  • See? It was so hard to create a [mcve]? I will try to reproduce the code to see if I can locate the error.

  • Did you ever read my answer? Why, by coincidence, have I already quoted which error and how to correct.

1 answer

2


The added example only reinforces what I had already mentioned, that the cause of the problem is you apply a Systener within another Systener. In this section of the class 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");
        }
    });
}  

You start the other screen and at the same time add a new Systener to the boot of this new screen.

Here are two errors: one I have already mentioned, which is to add Listener inside another without any kind of control, and the other error is the encapsulation violation. If you don’t know what that is, I recommend you read it this answer from here even from the site to better understand.

What actually happens is not the execution of the same method twice, but the execution of the two listeners that you apply to the button, because in the class teste3 you had already added a Istener.

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");
}  

How to correct? Simple! Each window should be responsible for its components and the events within it that occur, so just separate the responsibility of each window within the class itself and not change component of one window into the other, as I have already mentioned, this violates encapsulation and is a bad practice of programming, when you do without having any idea what it means or the consequences that it can cause.

If jbutton1 belongs to the class teste3, leave everything event only in this class, and apply only one ActionListner, because you hardly need to apply more than one Switch of the same type to the same component, particularly I’ve never seen this kind of need.

I suggest you always start with java tutorials, and there’s also the tag here on the site with a lot of content, because if you want to mess with the api swing but not even aware of how it works, you will face this kind of difficulty and continue making this kind of implementation harmful to your application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.