1

So i am a beginner programmer and what I'm trying to do is to get specific button's text by knowing its fx:id Is it possible? For example if button fx:id = "buttonOne" and text = "X" how can I get X?

Omar AMEZOUG
  • 958
  • 2
  • 14
  • 38

1 Answers1

2

You can define your button in controller (fx:id should be equals name of the field):

@FXML
Button buttonOne;

And just use getText():

buttonOne.getText();
Egor
  • 1,334
  • 8
  • 22
  • It's a good solution but the thing is I'll have to create nine buttons just for checking text so I wondered if its possible to compare two different button texts without creating a new object – DudDerY DuDe Dec 13 '19 at 14:40
  • @DudDerYDuDe yes, you can get element by id. Try this: String text = ((Button) scene.lookup("#buttonOne")).getText(); – Egor Dec 13 '19 at 14:43
  • That's exactly what I was looking for.Thanks for help – DudDerY DuDe Dec 13 '19 at 14:46
  • I would not recommend the answer in the comment. See Jame D's comments [here](https://stackoverflow.com/questions/30685672/javafx-parent-lookup-returns-null). If you don't want to take the time to do as this answer suggests, you should try to put all the buttons into a parent element and retrieve them as children. Then you can loop through them looking for the id and return the Button with that id. – SedJ601 Dec 13 '19 at 14:54