Send back data to a java class?

Using Java, Netbeans.

So I have a JFrame[1] object, it really doesn’t matter how the class is constructed. In this JFrame object there is a button which triggers an event when clicked and a new window appear where the user gives some input. In this new window which is a different JFrame[2] object the input data is stored, how can I use this data in the first window object whenever the user clicks finished in the second window?

So my ultimate question is, how can I send back the data to the class? I have a reference pointing toward the second window object, however my solution requires two threads to be running, one that checks when the window disposes and one that keeps the window running. I don’t think this is the optimal way of doing this, can someone help?

[1] = first window;

[2] = second window;

Here is the code in the first class which constructs the second class.

    /**
    *
    * @param evt gets created when buttonObjectCreate is clicked. Creates a new
    * window for constructing a new GameCreator object.
    */
    private void buttonObjectCreateActionPerformed(java.awt.event.ActionEvent evt) {                                                   
           CreateNewObjectWindow createNewObjectWindow = new CreateNewObjectWindow();
           createNewObjectWindow.setVisible(true);
}    

And the second class is just a JFrame object with a String value and two integer values. After createNewObjectWindow is disposed, how can I use the data that was released in the class here?

Answer

The point is: in order to “exchange” anything, two things are required:

  1. The objects to exchange something, need to know each other …
  2. so that they can call methods of that other object at some time (or bad style: just write into fields of that other object).

If I get it right, your class 1 does

CreateNewObjectWindow createNewObjectWindow = new CreateNewObjectWindow();
       createNewObjectWindow.setVisible(true);

and createNewObjectWindow is that object of class 2 that should talk back.

And, obviously, that instance is created within that one method; and the reference to it thrown away afterwards. If you really want to know that object to be useful for the object that created, you need something like:

class A {
   private B myB;

   public void doSomething() { ... }

   public void createB() {
     myB = new B(this);
   }
}

class B {
   private A daddy;
   public B(A myDaddy) { this.daddy = myDaddy };

   public void doSomethingWithA() { daddy.doSomething(); }
}

In essence, that is all there is to this. If your problem is really that you don’t know how to do such things; then hint: don’t program Swing UI applications for now. Instead, learn the Java basics. It seems like you intend to build a house, but you have no idea how to hold the shovel to dig the hole for the basement yet.

Leave a Reply

Your email address will not be published. Required fields are marked *