tags:

views:

56

answers:

4

I have a form that is divided into two classes. Each class represents the widgets on part of the form. What is the best way to allow these classes to share data between each other and update each other.

Example: Button in class A is clicked. Update text field in class C

A: 

You could create a class that holds all your form-objects. The form classes all know the parent class and communicate over it.

If a button is clicked in class A, class A calls a method in the parent class and the parent class notifies class C to update its text field.

Ham
A: 

Don't think widget. Design your application on models. Have widgets as windows onto those models. (And don't extend classes unnecessarily.)

Tom Hawtin - tackline
+2  A: 

This is very short what you can do:

public class ButtonFrame extends JFrame implements ActionListener
{
     private TextFieldFrame frame;

     public ButtonFrame(TextFieldFrame frame)
     {
         this.frame = frame;
         // init your components and add this as actionlistener to the button
         ....
     }

     public void actionPerformed(ActionEvent evt)
     {
         frame.notifyButtonPressed();
     }
}

The other class:

public class TextFieldFrame extends JFrame
{
     private JTextField field = ...; // init in your constructor

     public void notifyButtonPressed()
     {
         field.setText("Yes man!! The button is pressed by the user!");
     }
}

Again, this is very short what you have to do.
You can also work with a Singleton pattern, but this is a better way.

Martijn Courteaux
A: 

Have a look at Mediator pattern, it could give you some ideas. mediator@wiki

Also, JFace Databinding framework goal is synchronization of values between objects, although i find it poorly documented and not much fun to use. JFace_Data_Binding

Svilen