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

时间:2016-10-25 14:35:06

标签: java swing

首先,我知道使用多个jframe是不受欢迎的,不幸的是我已经深入到这个项目重新开始了。我的问题是我找不到将数据(用户输入)从一帧传输到另一帧的方法,我将提供我需要从第1帧传输到另一帧的代码

这是我输入的名称和电子邮件的代码

    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) {

        }

这是转到新框架的按钮代码

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


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

我是新手,我不需要有人来完成我的计划。我只需要知道如何将它带到新框架上的新文本框中。

2 个答案:

答案 0 :(得分:0)

框架就像任何其他类一样,所以只需使用相同类型的策略在任何其他类之间传递数据。例如,您可以在第二个框架类中创建setter方法,并从第一个框架中调用它们。

注意:这只是我在Netbeans中快速拼凑的东西,所以有很多生成的代码。此外,这是一个严格的例子我不是说它必须是最好的方式。

以下是一个快速而又脏的示例,说明如何在两个JFrame对象之间传递数据:

这是从Frame1注意的代码:

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

以下是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                   
}

以下是Frame2的重要代码:

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

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

以下是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                   
}

答案 1 :(得分:0)

这样做很容易。您需要做的就是设置一个构造函数,在该构造函数中将您需要的值传递给新框架。

例如,我有一个LoginScreen.java和DoctorScreen.java。如果我的用户成功输入了他的详细信息并登录,我将一个DocList的ArrayList从一个JFrame转移到另一个JFrame,或者更准确地说,从一个java类转移到另一个java类,通过创建该类的新实例

此处示例

将一个arraylist从LoginScreen.java传递给DoctorScreen.java

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

现在获取从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();
}

现在,您可以更改DoctorScreen构造函数以适合您尝试执行的任何项目。

我建议您采取的步骤是创建一个用于处理输入的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
}

}

然后在你的display.java中,调用构造函数接收这些字段并在textfield / textarea或框架中的JLabel中显示它们

 String name, field1, field2;

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

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

请注意,这些变量已经声明,我只是用于演示目的。