将一个JavaFX方法用于多个按钮 [英] Using one JavaFX method for multiple Buttons

查看:566
本文介绍了将一个JavaFX方法用于多个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用Eclipse Luna,JavaFX和SceneBuilder。我有~40个按钮,我想使用每个按钮都可以使用的通用buttonPressed动作方法。这样的事情:

Right now I'm using Eclipse Luna, JavaFX and SceneBuilder. I have ~40 buttons, and I'd like to use a generic "buttonPressed" action method that every button can use. Something like this:

public void buttonPressed(ActionEvent event, Button b) {
    b.setText("Pressed");
}

当我在SceneBuilder中更改On Action面板时,我得到以下异常当我尝试运行我的程序时:

When I change the On Action panel in SceneBuilder however, I get the following Exception when I try to run my program:


javafx.fxml.LoadException:错误解析onAction ='#buttonPressed',事件处理程序是不在命名空间或脚本中有错误。

javafx.fxml.LoadException: Error resolving onAction='#buttonPressed', either the event handler is not in the Namespace or there is an error in the script.

我错过了一个步骤吗?或者有没有人知道使用一种方法来控制多个按钮的点击行为的另一种方法?

Is there a step I missed? Or does anyone know of an alternate way to use one method to control the on-click behavior of multiple buttons?

任何帮助表示赞赏!

推荐答案

在评论中, onAction 属性允许的唯一签名是零参数,或者是单个参数,它是 ActionEvent

As in your comment, the only signatures allowed for an onAction attribute are either zero arguments, or a single argument which is an ActionEvent.

您可以按如下方式获取事件的来源:

You can get the source of the event as follows:

@FXML
public void buttonPressed(ActionEvent event) {
    Object source = event.getSource();
    // ...
}

当然如果你认识你只能在按钮上注册处理程序,你可以做到

and of course if you know you only registered the handler on buttons, you can do

@FXML
public void buttonPressed(ActionEvent event) {
    Button button = (Button) event.getSource();
    // ...
}

这篇关于将一个JavaFX方法用于多个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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