Xander
Xander

Reputation: 9171

Communicating between classes

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

Upvotes: 1

Views: 2684

Answers (4)

Svilen
Svilen

Reputation: 1437

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

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

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68857

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.

Upvotes: 3

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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

Upvotes: 0

Ham Vocke
Ham Vocke

Reputation: 2994

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.

Upvotes: 0

Related Questions