Home > database >  How can I transfer data between one jframe to another jframe?
How can I transfer data between one jframe to another jframe?

Time:11-15

I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!

package eventdriven;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class EventDriven extends JFrame {
    
    JPanel items = new JPanel();
    
    JLabel fName = new JLabel("First Name: ");
    JLabel lName = new JLabel("Last Name: ");
    JLabel mName = new JLabel("Middle Name: ");
    JLabel mNum = new JLabel("Mobile Number: ");
    JLabel eAdd = new JLabel("Email Address: ");
    
    JTextField fname = new JTextField(15);
    JTextField lname = new JTextField(15);
    JTextField mname = new JTextField(15);
    JTextField mnum = new JTextField(15);
    JTextField eadd = new JTextField(15);

    JButton submit = new JButton("Submit");
    JButton clear = new JButton("Clear All");
    JButton okay = new JButton("Okay");
    
    JTextArea infos;
    JFrame output;
    
    public EventDriven()
    {
        this.setTitle("INPUT");
        this.setResizable(false);
        this.setSize(230, 300);
        this.setLocation(300, 300);
        this.setLayout(new FlowLayout(FlowLayout.CENTER));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        this.add(fName);
        this.add(fname);
        this.add(lName);
        this.add(lname);
        this.add(mName);
        this.add(mname);
        this.add(mNum);
        this.add(mnum);
        this.add(eAdd);
        this.add(eadd);
       
        submit.addActionListener(new btnSubmit());
        this.add(submit);
        clear.addActionListener(new btnClearAll());
        this.add(clear);
        okay.addActionListener(new btnOkay());
        
        
        this.add(items);
        this.setVisible(true);
    }
    
    class btnSubmit implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getSource() == submit)
            {
            submit.setEnabled(false);
            output = new JFrame("OUTPUT");
            output.show();
            output.setSize(300,280);
            output.setTitle("OUTPUT");
           
            
            output.add(okay);
            output.setLayout(new FlowLayout(FlowLayout.CENTER));
            }   
        }
    }
    
    class btnClearAll implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getSource() == clear)
            {
                fname.setText(null);
                lname.setText(null);
                mname.setText(null);
                mnum.setText(null);
                eadd.setText(null);
                submit.setEnabled(true);
                output.dispose();
            }
        }   
    }
    
    class btnOkay implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getSource() == okay)
            {
                fname.setText(null);
                lname.setText(null);
                mname.setText(null);
                mnum.setText(null);
                eadd.setText(null);
                submit.setEnabled(true);
                output.dispose();
            }
        }    
    }
    
    public static void main(String[] args) 
    {   
        EventDriven window = new EventDriven();  
    }  
}

CodePudding user response:

It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):

public class EventDriven extends JFrame {
    private final JTextField nameField = new JTextField(15);
    private final JButton submit = new JButton("Submit");
    private final JButton clear = new JButton("Clear All");

    public EventDriven() {
        setTitle("Input");
        setLayout(new FlowLayout(FlowLayout.CENTER));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(new JLabel("Name: "));
        add(nameField);
        submit.addActionListener(this::showOutput);
        add(submit);
        clear.addActionListener(this::clearInput);
        add(clear);
        pack();
    }

    private void showOutput(ActionEvent ev) {
        submit.setEnabled(false);
        JDialog output = new JDialog(EventDriven.this, "Output", true);
        output.add(new Label("Name: "   nameField.getText()), BorderLayout.CENTER);
        JButton okButton = new JButton("OK");
        output.add(okButton, BorderLayout.SOUTH);
        okButton.addActionListener(bv -> output.setVisible(false));
        output.pack();
        output.setVisible(true);
    }

    private void clearInput(ActionEvent ev) {
        nameField.setText(null);
        submit.setEnabled(true);
    }

    public static void main(String[] args) {
        EventDriven window = new EventDriven();
        window.setVisible(true);
    }
}

You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s

CodePudding user response:

You need to use Constructor Overloading to transfer data one frame to another fram. Here down is example of transfer data from FirstForm to SecondForm

FirstForm.java

public class FirstForm extends javax.swing.JFrame {

    public FirstForm() {
        initComponents();
    }

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

        lblName = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        btnSubmit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblName.setText("First Name:");

        btnSubmit.setText("Submit");
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(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(103, 103, 103)
                .addComponent(lblName)
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSubmit)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(88, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(52, 52, 52)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblName)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnSubmit)
                .addContainerGap(187, Short.MAX_VALUE))
        );

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

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                          
        SecondForm sf = new SecondForm(lblName.getText(), txtName.getText());
        sf.setVisible(true);
        dispose();
    }                                         

    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 ex) {
            java.util.logging.Logger.getLogger(FirstForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FirstForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FirstForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FirstForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FirstForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnSubmit;
    private javax.swing.JLabel lblName;
    private javax.swing.JTextField txtName;
    // End of variables declaration                   
}

SecondForm.java

public class SecondForm extends javax.swing.JFrame {
    public SecondForm() {
        initComponents();
    }
    
    public static String lblName,txtName;
    public SecondForm(String lblName, String txtName)
    {
        this.lblName=lblName;
        this.txtName=txtName;
        initComponents();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        LblName = new javax.swing.JLabel();
        TxtName = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        LblName.setText("jLabel1");

        TxtName.setText("jLabel2");

        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(124, 124, 124)
                .addComponent(LblName)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(TxtName)
                .addContainerGap(198, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(120, 120, 120)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LblName)
                    .addComponent(TxtName))
                .addContainerGap(166, Short.MAX_VALUE))
        );

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

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        LblName.setText(lblName);
        TxtName.setText(txtName);
    }                                 

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

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SecondForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel LblName;
    private javax.swing.JLabel TxtName;
    // End of variables declaration                   
}

  • Related