【问题标题】:passing information from one jframe to another将信息从一个 jframe 传递到另一个
【发布时间】:2016-10-25 14:35:06
【问题描述】:

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

这是他们必须输入的姓名和电子邮件的代码

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

我是摇摆新手,我不需要有人来完成我的程序。我只需要知道如何将它转移到新框架上的新文本框。

【问题讨论】:

  • 不知道你在哪里弄糊涂了,你只需要在JTextArea上使用getText(),在另一个上使用setText()。你能提供课程的全部代码吗?
  • “我已经让自己深入到这个项目中重新开始。” 运气不好。继续处理固有的损坏代码是没有意义的。修复这个烂摊子比重构应用程序需要更长的时间。 天生就坏了。
  • 我投票决定将此问题作为题外话结束,因为 OP 正试图修复一种固有的破坏方法。我们无法用创可贴修复断腿。
  • txtrEnterYourFull.setBounds(52, 58, 166, 29); Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
  • 我觉得这个问题是重复的,在这里你可以找到答案:stackoverflow.com/questions/20382999/…

标签: java swing


【解决方案1】:

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

例如,我有一个 LoginScreen.java 和 DoctorScreen.java。如果我的用户成功输入了他的详细信息并登录,我将一个医生的 ArrayList 从一个 JFrame 传输到另一个 JFrame,或者更准确地说,通过创建该类的新实例从一个 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 文件来显示您在第一个文件中输入的内容

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

 String name, field1, field2;

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 你能编辑你的答案并删除多余的位吗?或者我可以吗?
    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2019-11-19
    • 2015-07-04
    • 2016-04-16
    相关资源
    最近更新 更多