对多个按钮使用一种 JavaFX 方法
Using one JavaFX method for multiple Buttons
现在我正在使用 Eclipse Luna、JavaFX 和 SceneBuilder。我有大约 40 个按钮,我想使用每个按钮都可以使用的通用 "buttonPressed" 操作方法。像这样:
public void buttonPressed(ActionEvent event, Button b) {
b.setText("Pressed");
}
然而,当我在 SceneBuilder 中更改 On Action 面板时,当我尝试 运行 我的程序时出现以下异常:
javafx.fxml.LoadException: Error resolving onAction='#buttonPressed', either the event handler is not in the Namespace or there is an error in the script.
有没有漏掉的步骤?或者有人知道使用一种方法来控制多个按钮的点击行为的替代方法吗?
感谢任何帮助!
在您的评论中,onAction
属性允许的唯一签名是零参数,或者是 ActionEvent
.
的单个参数
您可以通过以下方式获取事件来源:
@FXML
public void buttonPressed(ActionEvent event) {
Object source = event.getSource();
// ...
}
当然,如果您知道您只在按钮上注册了处理程序,您可以这样做
@FXML
public void buttonPressed(ActionEvent event) {
Button button = (Button) event.getSource();
// ...
}
现在我正在使用 Eclipse Luna、JavaFX 和 SceneBuilder。我有大约 40 个按钮,我想使用每个按钮都可以使用的通用 "buttonPressed" 操作方法。像这样:
public void buttonPressed(ActionEvent event, Button b) {
b.setText("Pressed");
}
然而,当我在 SceneBuilder 中更改 On Action 面板时,当我尝试 运行 我的程序时出现以下异常:
javafx.fxml.LoadException: Error resolving onAction='#buttonPressed', either the event handler is not in the Namespace or there is an error in the script.
有没有漏掉的步骤?或者有人知道使用一种方法来控制多个按钮的点击行为的替代方法吗?
感谢任何帮助!
在您的评论中,onAction
属性允许的唯一签名是零参数,或者是 ActionEvent
.
您可以通过以下方式获取事件来源:
@FXML
public void buttonPressed(ActionEvent event) {
Object source = event.getSource();
// ...
}
当然,如果您知道您只在按钮上注册了处理程序,您可以这样做
@FXML
public void buttonPressed(ActionEvent event) {
Button button = (Button) event.getSource();
// ...
}