繁体   English   中英

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

[英]passing information from one jframe to another

首先,我知道使用多个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();

我是新人,我不需要别人来完成我的程序。 我只需要知道如何将其携带到新框架上的新文本框中即可。

框架与其他任何类一样,因此只需使用与其他任何类之间传递数据所使用的策略相同的策略即可。 例如,您可以在第二个框架类中简单地创建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                   
}

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

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

这里的例子

将数组列表从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文件显示您在第一个文件中输入的内容

例如:

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中,调用构造函数并接受这些字段,并在文本字段/文本区域或框架中的JLabel中显示它们

 String name, field1, field2;

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

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

请注意,这些变量已被声明,我仅将其用于演示目的。

暂无
暂无

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

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