简体   繁体   中英

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

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM