I am doing a project using Java swing in Netbeans and I am using their in-built GUI generator thing. I have created a socket in one frame and i need to use the same object in another frame. these frames are present in the same package but are different classes.

Please tell me how to use that object in another frame!

Recommended Answers

All 5 Replies

first of all, never use the automatic GUI generator... as it is very hard to read/re-use/edit...

always create your GUIs yourself... it may take a lil longer but is much more worth the trouble at the end.

note:sorry for the hate and off topic, just it'll help alot later on

In the same way you do it in any other class with any other object.
In one class make that object as a global attribute and either set it to be public or use get/set methods.

public class OneFrame {
  public SomeObject so = null;
  // create it in this class and do things with it

  public OneFrame() {
    so = new SomeObject();
  }
}

Since you didn't explain your problem very well, I am going to assume that when you click a button in this frame another opens and you want that object to be passed to the other frame?
Then at the second frame have the constructor take as parameter that object and pass the one you have at first frame as parameter.

public class OneFrame {
  public SomeObject so = null;
  // create it in this class and do things with it

  public OneFrame() {
    so = new SomeObject();
  }

  private void openNewFrame() {
    NewFrame nf = new NewFrame(so);
  }
}
public class NewFrame{
  public SomeObject so = null;

  public NewFrame(SomeObject so) {
    this.so = so;
  }
}

Thanks javaAddict!
That really solved my problem! Thanks!!!

Can I ask a follow up question? In the definition of the new frame:

public class NewFrame{
  public SomeObject so = null;

  public NewFrame(SomeObject so) {
    this.so = so;
  }
}

You have passed the SomeObject but in the 

 public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewFrame().setVisible(true);
            }
        });
    }

I can't add the SomeObject to new NewFrame().... (I get an error)

The original question was how to pass an object to a subsequent frame. That presupposes that NewFrame is dependent upon the object, which has already been created. In your example, that does not apply. If you don't have SomeObject you need to pass along, then there is no point in even creating the NewFrame constructor that accepts SomeObject - just use the plain empty constructor.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.