Calling Jbuton from one Jframe to another

Asked

Viewed 1,002 times

0

I’m a beginner in this area, and I’m having a little bit of a problem, so if you could help me..

I have two Frames one is main (P) and the other (B) I call through a button. On the main screen I have two buttons register and access, when I run the main screen appears, the register button does not appear (this is intentional) being visible only the access button, when clicking the access button it calls the frame (B) which finally has two buttons, confirm and cancel, when clicking the confirm button it returns to the main frame (P), this time with the sign up button visible, but I have no idea how to use the sign up button of the frame (P) in the frame (B).

I will submit the complete code as I am doing in netbeans will get a little long.. This is the Main class that when you click on the Access button will open the screen of frame B.

package javaapplication2;

public class Principal extends javax.swing.JFrame {

    /**
     * Creates new form Principal
     */
    public Principal() {
        initComponents();
        JBCadastrar.setVisible(false);


    }

    /**
     * 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() {

        JBCadastrar = new javax.swing.JButton();
        JBAcessar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        JBCadastrar.setText("Cadastrar");

        JBAcessar.setText("Acessar");
        JBAcessar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBAcessarActionPerformed(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(147, 147, 147)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(JBCadastrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(JBAcessar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(172, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(106, 106, 106)
                .addComponent(JBCadastrar)
                .addGap(38, 38, 38)
                .addComponent(JBAcessar)
                .addContainerGap(110, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(416, 338));
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void JBAcessarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String args [] = new String [1];
        FrameB1.main(args);

    }                                         

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

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

This other one is Frameb1

package javaapplication2;

public class FrameB1 extends javax.swing.JFrame {

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

        JBConfirmar = new javax.swing.JButton();
        JBCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        JBConfirmar.setText("Confirmar");
        JBConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBConfirmarActionPerformed(evt);
            }
        });

        JBCancelar.setText("Cancelar");
        JBCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBCancelarActionPerformed(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(70, 70, 70)
                .addComponent(JBConfirmar)
                .addGap(76, 76, 76)
                .addComponent(JBCancelar)
                .addContainerGap(100, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(124, 124, 124)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JBConfirmar)
                    .addComponent(JBCancelar))
                .addContainerGap(153, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(416, 338));
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void JBConfirmarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        String args [] = new String [1];
        Principal.main(args);
        dispose();
    }                                           

    private void JBCancelarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        dispose();
    }                                          

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

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

Then, note that in the first frame I left the invisible sign-up button and when I click access will call the screen frameB1,and when I launch the confirm button will close the window of frameB1 calling back the main frame already with the sign up visible. but I’m not able to do it...

1 answer

0


Let’s do what your class buttons do Principal:

    private void JBAcessarActionPerformed(java.awt.event.ActionEvent evt) {
        String args [] = new String [1];
        FrameB1.main(args);

    }

Let’s see your class FrameB1:

    private void JBConfirmarActionPerformed(java.awt.event.ActionEvent evt) {
        String args [] = new String [1];
        Principal.main(args);
        dispose();
    }        

    private void JBCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }

You have two methods main here, one in each class, which is wrong. You should have only one method main and should never invoke him directly.

Your mistake is to stick to the idea that only one screen is active at a time and forget that these are objects. Instead, separate a file called Main.java:

package javaapplication2;

public class Main {
    public static void main(String[] args) {
        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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(() -> new Principal().setVisible(true));
    }
}

In your class FrameB1, change this:

    public FrameB1() {
        initComponents();
    }

That’s why:

    private final Principal telaPrincipal;

    public FrameB1(Principal telaPrincipal) {
        this.telaPrincipal = telaPrincipal;
        initComponents();
    }

And also this:

    private void JBConfirmarActionPerformed(java.awt.event.ActionEvent evt) {
        String args [] = new String [1];
        Principal.main(args);
        dispose();
    } 

    private void JBCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }

That’s why:

    private void JBConfirmarActionPerformed(java.awt.event.ActionEvent evt) {
        telaPrincipal.reativar(true);
        dispose();
    } 

    private void JBCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        telaPrincipal.dispose();
        dispose();
    }

In your class Principal, add this method:

    public void reativar(boolean botaoCadastrarVisivel) {
        setVisible(true);
        JBCadastrar.setVisible(botaoCadastrarVisivel);
    }

Change that method:

    private void JBAcessarActionPerformed(java.awt.event.ActionEvent evt) {
        String args [] = new String [1];
        FrameB1.main(args);

    }

That’s why:

    private void JBAcessarActionPerformed(java.awt.event.ActionEvent evt) {
        FrameB1 fb = new FrameB1(this);
        setVisible(false);
    }

And then, you can withdraw the method main of both classes Principal and FrameB1.

  • thank you worked out.

  • @Joshua If this answer solved your problem and you have no more questions, mark it as accepted/correct by clicking on " " here on the side, which also marks your question as answered/solved. If on the other hand you are not yet satisfied, leave a comment and we will clarify.

Browser other questions tagged

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