NetBeans Forums

 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister   ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 
  

how to get value from 1stFrame to 2ndFrame?

 
Post new topic   Reply to topic    NetBeans Forums -> NetBeans Users
View previous topic :: View next topic  
Author Message
zacix



Joined: 11 Jun 2012
Posts: 6

PostPosted: Wed Jun 20, 2012 10:00 am    Post subject: how to get value from 1stFrame to 2ndFrame? Reply with quote

Im am new to Java and netbeans. need help.

In my "First" frame:
I accept textfield (e.g. name) from user, then user click button OK.
then jump to Second form, I want to display name in my Second frame jlabel,
how can I do it?

Following are my code in First Frame and User.java

---------------------------------------------------------------------------------
//First frame
public static User x;
private void btn_nextActionPerformed(java.awt.event.ActionEvent evt) {
String a = name.getText();
x = new User(a) //store name into User class

Second frame2 = new Second(); //open Second frame
this.setVisible(false);
frame2.setVisible(true);

---------------------------------------------------------------------------------
//User class

public class User{

private String name;

public User(String a){
name = a;
}
}
----------------------------------------------------------------------------------
Back to top
bolsover



Joined: 24 Jun 2010
Posts: 185

PostPosted: Wed Jun 20, 2012 7:34 pm    Post subject: Reply with quote

I suggest you implement PropertyChangeListener in frame2 and fire PropertyChangeEvent from frame1
Back to top
Bayless Kirtley
Posted via mailing list.





PostPosted: Wed Jun 20, 2012 8:21 pm    Post subject: how to get value from 1stFrame to 2ndFrame? Reply with quote

You're making it a bit harder than needed. Let Netbeans create your second
frame then manually add a new constructor to it that accepts your name. Then
instantiate your second frame passing the name as the constructor argument,

Second frane2 = new Second(a);

That is one simple way.


-----Original Message-----
From: zacix
Sent: Wednesday, June 20, 2012 5:00 AM
To: address-removed
Subject: [nbusers] how to get value from 1stFrame to 2ndFrame?

Im am new to Java and netbeans. need help.

In my "First" frame:
I accept textfield (e.g. name) from user, then user click button OK.
then jump to Second form, I want to display name in my Second frame jlabel,
how can I do it?

Following are my code in First Frame and User.java

---------------------------------------------------------------------------------
//First frame
public static User x;
private void btn_nextActionPerformed(java.awt.event.ActionEvent evt) {
String a = name.getText();
x = new User(a) //store name into User class

Second frame2 = new Second(); //open Second frame
this.setVisible(false);
frame2.setVisible(true);

---------------------------------------------------------------------------------
//User class

public class User{

private String name;

public User(String a){
name = a;
}
}
----------------------------------------------------------------------------------






-----
No virus found in this message.
Checked by AVG - www.avg.com
Version: 2012.0.2180 / Virus Database: 2437/5081 - Release Date: 06/20/12
Back to top
bolsover



Joined: 24 Jun 2010
Posts: 185

PostPosted: Thu Jun 21, 2012 10:14 am    Post subject: Reply with quote

Yes indeed, passing the name value as a constructor argument is easier... but a less flexible solution - users often want to have both frames open and pass data between the two.

How about beansbinding as another alternative?
Back to top
zacix



Joined: 11 Jun 2012
Posts: 6

PostPosted: Thu Jun 21, 2012 5:15 pm    Post subject: Reply with quote

thx Bayless Kirtley.

bolsover, I do not know about beansbinding yet.


I want to create Java GUI Application by netbeans, do I need to create a "Main.java" class (no design interface) as Main Class?

how can I get input value from JFrame form (e.g. First.java), and pass into Main.class for further data manipulation?
Back to top
SearchEngine27



Joined: 21 Jun 2012
Posts: 66

PostPosted: Thu Jun 21, 2012 5:52 pm    Post subject: Reply with quote

As mentioned before, whether you're just trying to get a value from one window, close it, and then open up a second video with that information, then all you really have to do is create a listener.

for closing the first window and then opening a second with that information, you would set an action listener on whatever it is you're using to close the first window
i.e.
Code:

public class GUI extends JFrame{
    public String storedText;
    public GUI(){
    JButton nextFrame = new JButton("Close 1st Frame");
    nextFrame.addActionListener(new ActionListener(){
      void actionPerformed(ActionEvent evt){
        GUI parent = evt.getParentFrame(); //dont remember the exact method name but its something like that
        parent.storedText = txtArea.getText();  //store this somewhere
      }
    });
  }
}

and this way u have the data however you want

or if you want to do it as another use said, where you have 2 windows running simultaneously, then you will want to do something similar, but put a listener on the text field itself, and have it notify you of a change in value.
Back to top
bolsover



Joined: 24 Jun 2010
Posts: 185

PostPosted: Thu Jun 21, 2012 7:15 pm    Post subject: Reply with quote

zacix

As you will gather, there are several ways to solve the problem of passing data from one frame to another; none of the solutions discussed is 'right' - they each have their own merits. Which you choose depends on what you need to achieve.

Passing the name as a parameter as suggested by Bayless is just fine if you don't need to have frame2 updated again after it is first displayed. If you do need further updates to frame2 (such as typing into a textBox in frame1 and having the data also appear in frame2) then the technique I described is probably more apporpriate.

to give you an idea how easy this is...
I just created two JFrame: Frame1 and Frame2

I added a JButton and JTextField to Frame1 and a JTextField to Frame2
I then added an ActionListener to JButton and KeyListener to JTextField in Frame1.
Finally, I implemented PropertyChangeListener in Frame2 with the appropriate propertyChange(PropertyChangeEvent evt) method.
The action method bodies are detailed in the code below.


Frame1
Code:
package famesdemo;

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

        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setText("some text");
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(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()
                .addGap(84, 84, 84)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(36, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(43, Short.MAX_VALUE))
        );

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

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
        firePropertyChange("jTextField1KeyReleased", "", jTextField1.getText());
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Frame2 frame2 = new Frame2();
        this.addPropertyChangeListener(frame2);
        frame2.setVisible(true);
        firePropertyChange("jButton1ActionPerformed", "",  jTextField1.getText());
    }

    /**
     * @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.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}


Frame2
Code:
package famesdemo;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;



/**
 *
 * @author
 */
public class Frame2 extends javax.swing.JFrame implements PropertyChangeListener{
   
       /**
     * Creates new form Frame2
     */
    public Frame2() {
       initComponents();
    }
   
   
   

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals("jButton1ActionPerformed")){
            System.out.println("button in frame1 was pressed");
            this.jTextField1.setText((String)evt.getNewValue());
        }
        if (evt.getPropertyName().equals("jTextField1KeyReleased")){
            System.out.println("user typed in frame1 jTextField");
            this.jTextField1.setText((String)evt.getNewValue());
        }
    }

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

        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setText("jTextField1");

        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(39, 39, 39)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(59, Short.MAX_VALUE))
        );

        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.JTextField jTextField1;
    // End of variables declaration
}


Main.java - not really needed - you will see that both the frames in the code above have main methods because that is what Netbeans generates by default - you should launch from Frame1 and could delete the main method in Frame2

The entry point into a Java app can be any class with a main method. Using Netbeans, you choose which class is your entry point in the Project Properties dialog under the Run category.
Back to top
Display posts from previous:   
Post new topic   Reply to topic    NetBeans Forums -> NetBeans Users All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum


Powered by phpBB
By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo