班级间交流 [英] Communicating between classes

查看:24
本文介绍了班级间交流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分为两类的表格.每个类代表表单的一部分上的小部件.允许这些类在彼此之间共享数据并相互更新的最佳方式是什么.

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.

示例:单击 A 类中的按钮.更新类 C 中的文本字段

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();
     }
}

其他类:

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!");
     }
}

再说一次,您要做的事情很短.
您还可以使用 Singleton 模式,但这是更好的方法.

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

这篇关于班级间交流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆