Communicating between classes

不问归期 提交于 2019-12-23 01:14:01

问题


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


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/2772943/communicating-between-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!