0

I have a group of ToggleButtons that need to find out their id. Currently I can check the id in the getSource() and toString() method like this:

@FXML
public void btnCell(ActionEvent actionEvent) {
    System.out.println(actionEvent.getSource());
}

Prints: ToggleButton[id=btn00, styleClass=toggle-button]''

Can I extract the id without relying on some shady substring busniess on that string?

knut5
  • 1
  • 1
  • 2
  • Try the approach shown [here](https://stackoverflow.com/a/7706684/230513), then please [edit] your question to include a [mcve] that shows your revised approach. – trashgod Aug 31 '17 at 10:46
  • That example is of no use to me as I don't know which row or column the button is in. – knut5 Aug 31 '17 at 11:11
  • 2
    If you really want the id, just downcast the source to a `Node` and call `getId()`. But it is far better to register a different listener with each button (so you automatically know which button has triggered the event, because you know which button the listener was registered with). This is the way it is done in the answer linked above. It's not at all clear why you can't use that approach. – James_D Aug 31 '17 at 12:47
  • It will just give me alot of unnessary code as all methods should do the same thing basicly, they are bricks in a board game. – knut5 Aug 31 '17 at 17:50
  • @knut: The row and column are passed as parameters to `createGridButton()`; the nested listener uses them in a call to `getGridButton()`. Alternatively, you can `setId()` to any string you want. – trashgod Sep 01 '17 at 00:11

2 Answers2

1

hope it helps:

import javafx.scene.Node;
.... 
@FXML
public void btnCell(ActionEvent actionEvent) {
   final Node source = (Node) actionEvent.getSource();
   String id = source.getId();
   Scene scene = source.getScene();
   scene.lookup("#"+id).getStyleClass() ;
}
Babak Hashemi
  • 327
  • 3
  • 11
0

In case this is still relevant, I use a whole bunch of programmatically generated buttons (representing menu items in a POS application), identified through MyButton.setUserData(MyProdID), which is loaded from the product IDs in a database table. Then you can get that with MyButton.getUserData() in the ActionEvent handler.

Joe1962
  • 11
  • 3