Java:将事件传递给另一个组件
抱歉,我不知道这是否很清楚,但我对 Java 还很陌生。
所以我有一个带有 BorderLayout 的 JFrame,其中包含一个 JPanel 和一个 JButton。
我想要做的是,当我的 JPanel 中发生某些情况时,我想要更改 JButton 的文本,或者启用/禁用它。我该怎么做呢?如何从 JPanel 访问 JButton?我知道一些方法,但我认为它们不是最好的方法。
最好的方法是什么?
提前致谢
Sorry I don't know if this is very clear, but I'm pretty new to Java.
So I have a JFrame with a BorderLayout containing a JPanel and a JButton.
What I want to do is when something happens in my JPanel, I want for example change the text of the JButton, or enable/disable it. How would I do that? How can I access the JButton from the JPanel? I know some ways of doing it but I don't think they're the best way to do it.
What would be the best way to do this?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的情况是当您的 JPanel 实例和 JButton 实例在代码中“看到”彼此时,即:
处理程序中的第二个组件:
在这种情况下,您可以向面板(或按钮)添加一些事件侦听器并更改事件 这里唯一需要注意的是,您应该在
button
声明附近使用final
修饰符(因为 java 没有真正的闭包):更复杂的情况是当您的组件不这样做时彼此不了解,也不知道系统状态何时更改,并且组件状态(例如按钮名称或更严重的内容)也应该更改。在这种情况下,您应该考虑使用 MVC 模式。这是来自 JavaWorld 的一个非常好的教程:MVC 遇见 Swing。
The most simple case is when your JPanel instance and JButton instance "see" each other in your code i.e.:
In that case you can add some event listener to your panel (or to your button) and change the second component from event handler:
The only thing you should count here is that you should use
final
modifier nearbutton
declaration (due to java doesn't have real closures):More complicated case is when your components don't know about each other or when system state is changed and components state (like button name or something more serious) should be changed too. In this case you should consider using MVC pattern. Here is a very nice tutorial from JavaWorld: MVC meets Swing.
您必须监听 JPanel 上的事件。 JPanel 可以监听按键 (KeyListener)、鼠标单击 (MouseListener) 和鼠标移动 (MouseMovementListener)。您对哪一个感兴趣?
一旦你知道你想听什么,你就必须编写并注册一个监听器,并在 JButton 中更改一些内容。例如:
You have to listen to an event on your JPanel. JPanels can listen to key presses (KeyListener ), mouse clicks (MouseListener), and mouse movements (MouseMovementListener). Which one are you interested in?
Once you know what you want to listen to, you have to write and register a listener, and change something in the JButton. For example: