簡體   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