首页 > java > Java Swing:Button的特定ID。如何在不使用.getActionCommand的情况下捕获监听器中的按下按钮?

Java Swing:Button的特定ID。如何在不使用.getActionCommand的情况下捕获监听器中的按下按钮? (Java Swing: Button's specific id. How can I catch pressed button in listener not using .getActio)

问题

我必须将一个ActionListener写入JPanel。

任务,取决于按下按钮以引起所需的操作。我知道的唯一方法 - 从按钮获取标签event.getActionCommand()并依赖于该字符串来引发所需的操作。

但我认为对标签进行绑定是错误的方式,非常错误的方式。还有其他选择吗?

换句话说,我的问题是:我如何确定按下的按钮?

解决方法

Swing是一个事件驱动的架构。因此,无论何时尝试与组件执行任何类型的交互,理想情况下都可以捕获或使用与组件关联的相应事件。

你需要做的是添加一个ActionListener,当执行一个动作时(在这种情况下按下按钮),你将调用你在代码中讨论的方法(“必需的动作”)。如果您是ActionListener的新手,您可能会发现:“如何编写动作侦听器”以提供帮助

问题

I have to write an ActionListener to JPanel.

The task, depending on the button pressed to cause the required action. The only way that I know - to get the label from the button using event.getActionCommand() and depending on that string to cause the desired action.

But I think that to have a binding to the label is wrong way, very wrong way. Are there other options?

In other words my question is: How can I determinate pressed button?

解决方法

Swing is an event driven architecture. So whenever you're trying to perform any type of interaction with a component, you would ideally be capturing or working with the corresponding event associated with the component.

What you would need to do is add an ActionListener, and when an action is performed (pressing of the button in this case), you would be calling the method (the "required action") you were talking about in your code. If you're new to ActionListener, you might find: "How to Write an Action Listener" to be helpful

相似信息