繁体   English   中英

如何在一个 jframe 和另一个 jframe 之间传输数据?

[英]How can I transfer data between one jframe to another jframe?

我是 java 的新手,出于某种原因,我不知道在按下提交后从另一个框架传输数据的任何其他方法。 例如,它会显示 output 框架 label 和用户在第一框架中写的文本字段,如“名称:”用户名。如果您知道请发布我应该输入的代码,谢谢!

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

不清楚您在另一帧中显示一个字段的值时遇到了什么问题。 但这里有一个这样做的例子(为了演示,字段减少到一个):

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

您还将看到我已经简化了您的动作侦听器,以演示一种更简单的方法来响应用户驱动的 event.s

您需要使用Constructor Overloading将数据一帧传输到另一帧。 下面是从FirstFormSecondForm传输数据的SecondForm

第一表格.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                   
}

第二表格.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                   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM