在两个 JPanel 对象之间发送消息
我有一个包含 JPanel 的 Java JFrame。在该 JPanel 中,有两个独立的 JPanel。当用户单击第一个 JPanel 中的按钮时,需要向另一个 JPanel 发送一条消息,通知它单击了哪个按钮。在这样的对象之间发送消息的最简单方法是什么?
I have a Java JFrame containing a JPanel. Within that JPanel, there are two separate JPanels. When the user clicks a button in the first JPanel, a message needs to be sent to the other JPanel notifying it which button was clicked. What is the easiest way to send messages between objects like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于 mKorbel(以及原始海报):
我建议的是松散耦合,即一个 JPanel 不了解另一个 JPanel,并且所有连接都是通过某种控件完成的。例如,借用您的一些代码:
CopyTextNorthPanel2.java
CopyTextSouthPanel2.java
CopyTextControl2.java
CopyText2.java
For mKorbel (and the original poster):
What I'm recommending is looser coupling, that the one JPanel has no knowledge of the other JPanel and that all connections are done through a control of some sort. For instance, to borrow some of your code:
CopyTextNorthPanel2.java
CopyTextSouthPanel2.java
CopyTextControl2.java
CopyText2.java
您可以创建一个自定义事件,并将一个或多个侦听器附加到该事件。
正确的实现方法是让 Button ActionListener 触发事件,然后让两个面板成为该事件的侦听器。
You could create a custom event, and attach one or more listeners to it.
The proper way to implement is to have the Button ActionListener fire the event and then have your two panels be listeners for that event.
但实际上
,我认为是时候开始考虑设计模式了。您所描述的内容是 观察者模式和可能的命令模式
at the top of your class
But really, I think it is time to start thinking about design patterns. What you are describing is perfect candidate for the observer pattern and possibly the command pattern
例如,通过在类之间使用构造函数或(用于调试问题)使用
getParent()
从所需的JComponent
中提取值+
+
+
for example by using Constructor betweens Classes or (for debuging issue) extract value from desired
JComponent
(s) by usinggetParent()
+
+
+