3

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");
}

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: 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?

Any help appreciated!

1
  • Just to add to my initial question; It seems like the problem is passing Button b in as a parameter. Removing it, and specifying a button inside the method remedies the Exception ( but not the problem at hand, as the method can now only be used by one button ). Is there perhaps a different way of locating which button is being pressed and then passing that to the method? Commented Feb 2, 2015 at 21:23

1 Answer 1

4

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();
    // ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I was able to achieve my desired result :D I used the following: public void buttonPressed(ActionEvent event) { Object source = event.getSource(); ((Labeled) source).setText("1"); } The (Labeled) was an auto-generated fix that Eclipse put in though, and isn't something I've seen before. Do you know if this is a problem/bad practice?
I dislike downcasts generally. They are somewhat prone to runtime errors: for example if at a later date you registered your listener with something that wasn't a Labeled (e.g. a MenuItem) then your code would compile but you'd get runtime errors. Here it's probably an ok thing to do; if you're registering the button handler in FXML and you have many buttons it's your only option other than having one method for every button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.