简体   繁体   English

将信息从一个jframe传递到另一个

[英]passing information from one jframe to another

To begin with, I know that using multiple jframes is frowned upon, unfortunately i have gotten myself to deep into this project to start over. 首先,我知道使用多个jframe的想法很普遍,但是不幸的是,我已经开始深入研究这个项目了。 my issue is i cannot find a way to transfer data (user input) from one frame to another, i will provide the code i need to be transferred from frame 1 to another frame 我的问题是我找不到将数据(用户输入)从一帧传输到另一帧的方法,我将提供我需要从帧1传输到另一帧的代码

this is my code for the name and email they have to input 这是我输入的姓名和电子邮件的代码

    JTextArea txtrEnterYourFull = new JTextArea();
    txtrEnterYourFull.setEditable(false);
    txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
    txtrEnterYourFull.setBackground(Color.GRAY);
    txtrEnterYourFull.setText("Enter your full name");
    txtrEnterYourFull.setBounds(52, 58, 166, 29);
    frame.getContentPane().add(txtrEnterYourFull);



    nameL = new JTextField();
    nameL.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    }
    );
    nameL.setBackground(Color.LIGHT_GRAY);
    nameL.setBounds(52, 93, 284, 26);
    frame.getContentPane().add(nameL);
    nameL.setColumns(10);


    JTextArea txtroptionalEnterYour = new JTextArea();
    txtroptionalEnterYour.setEditable(false);
    txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
    txtroptionalEnterYour.setBackground(Color.GRAY);
    txtroptionalEnterYour.setText("(Optional) Enter your email");
    txtroptionalEnterYour.setBounds(52, 139, 193, 29);
    frame.getContentPane().add(txtroptionalEnterYour);

    textField_1 = new JTextField();
    textField_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }

here is the button code to go to the new frame 这是转到新框架的按钮代码

    JButton btnContinue = new JButton("Continue");
    btnContinue.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {


            frame2 fram = new frame2 ();
            fram.setVisible(true);
            frame.dispose();

i am new to swing and i dont need someone to complete my program. 我是新人,我不需要别人来完成我的程序。 i just need to know how to carry it over to a new text box on a new frame. 我只需要知道如何将其携带到新框架上的新文本框中即可。

Frames are like any other class, so just use the same kind of strategies you use to pass data between any other classes. 框架与其他任何类一样,因此只需使用与其他任何类之间传递数据所使用的策略相同的策略即可。 For example you can simply create setter methods in your second frame class and call them from the first frame. 例如,您可以在第二个框架类中简单地创建setter方法,然后从第一个框架中调用它们。

Note : This is just something I threw together really fast in Netbeans so there is a lot of generated code. 注意 :这只是我在Netbeans中非常快速地整合在一起的东西,因此生成了很多代码。 Also, this is strictly an example I'm not saying it's necessarily the best way to do this. 另外,这严格来说是一个例子,我并不是说这一定是最好的方法。

Here is a quick and dirty example of how you might pass data between two JFrame objects: 这是一个简单又肮脏的示例,说明如何在两个JFrame对象之间传递数据:

This is the code to pay attention to from Frame1: 这是Frame1要注意的代码:

private void sendToOtherFrameBtnActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        Frame2 otherFrame = new Frame2();
        otherFrame.setTextFieldText(jTextField1.getText());
        otherFrame.setTextAreaText(jTextArea1.getText());
        otherFrame.setVisible(true);
    }  

Here is the full code for Frame1: 这是Frame1的完整代码:

public class Frame1 extends javax.swing.JFrame {

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

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();
        sendToOtherFrameBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setText("text area data");
        jScrollPane1.setViewportView(jTextArea1);

        jTextField1.setText("text field data");

        sendToOtherFrameBtn.setText("Send To Other Frame");
        sendToOtherFrameBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendToOtherFrameBtnActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(99, 99, 99)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(115, 115, 115)
                        .addComponent(sendToOtherFrameBtn)))
                .addContainerGap(135, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                .addComponent(sendToOtherFrameBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );

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

    private void sendToOtherFrameBtnActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        Frame2 otherFrame = new Frame2();
        otherFrame.setTextFieldText(jTextField1.getText());
        otherFrame.setTextAreaText(jTextArea1.getText());
        otherFrame.setVisible(true);
    }                                                   

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

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton sendToOtherFrameBtn;
    // End of variables declaration                   
}

Here is the important code from Frame2: 这是来自Frame2的重要代码:

public void setTextFieldText(String txt){
    jTextField1.setText(txt);
}

public void setTextAreaText(String txt){
    jTextArea1.setText(txt);
}

Here is the full code for Frame2: 这是Frame2的完整代码:

public class Frame2 extends javax.swing.JFrame {

    /**
     * Creates new form Frame2
     */
    public Frame2() {
        initComponents();
    }

    public void setTextFieldText(String txt){
        jTextField1.setText(txt);
    }

    public void setTextAreaText(String txt){
        jTextArea1.setText(txt);
    }

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

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        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(111, 111, 111)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jTextField1))
                .addContainerGap(123, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(52, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(99, 99, 99))
        );

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

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

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

Doing this is fairly easy. 这样做很容易。 All you need to do is to set a constructor in which you are passing your frame with the values you need over to your new frame. 您需要做的就是设置一个构造函数,在该构造函数中,将需要的值传递给新框架。

For example, I have a LoginScreen.java and DoctorScreen.java. 例如,我有一个LoginScreen.java和DoctorScreen.java。 If my user successfully entered his details and logs in, I transfer an ArrayList of Doctors from one JFrame to another JFrame, or more precisely, from one java class to another by creating a new instance of that class 如果我的用户成功输入了他的详细信息并登录,我将通过创建该类的新实例,将Doctors的ArrayList从一个JFrame传输到另一个JFrame,或更准确地说,从一个Java类传输到另一个Java类

Example here 这里的例子

Passing an arraylist from LoginScreen.java to DoctorScreen.java 将数组列表从LoginScreen.java传递到DoctorScreen.java

DoctorScreen dScreen = new DoctorScreen(frame, docList,d);

Now Taking those values passed from LoginScreen.java and setting them in DoctorScreen.java 现在,获取从LoginScreen.java传递的那些值,并在DoctorScreen.java中进行设置

public DoctorScreen(JFrame frame, ArrayList<Doctor> docList, Doctor d) {
    // TODO Auto-generated constructor stub
    dialog = new JFileChooser(System.getProperty("user.dir"));
    this.frame = frame;
    this.docList = docList;
    this.d = d;
    initialize();
}

Now, you can change the DoctorScreen Constructor to fit into whatever project you are trying to do. 现在,您可以更改DoctorScreen构造函数以适合您要执行的任何项目。

The steps I would advise you to take is to create a Java file for handling your input, and the second Java file to display what you entered in the first file 我建议您采取的步骤是创建一个Java文件来处理您的输入,第二个Java文件显示您在第一个文件中输入的内容

EG: 例如:

JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       String field1 = txtrEnterYourFull.getText();
       String name = nameL.getText();
       String field2 = txtroptionalEnterYour.getText();

       Display display = new Display(name, field1, field2);//using this as example
}

}

Then in your display.java, call your constructor taking in these fields and display them either in a textfield/textarea or in a JLabel in your frame 然后在display.java中,调用构造函数并接受这些字段,并在文本字段/文本区域或框架中的JLabel中显示它们

 String name, field1, field2;

 public Display(String name, String field1, String field2){

     this.name = name;
     this.field1 = field1;
     this.field2 - field2;
 }

Please take note that these variables have already been declared and I am merely using this for demonstration purposes. 请注意,这些变量已被声明,我仅将其用于演示目的。

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

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