Reputation: 393
Intellij IDEA + Oracle JDK 14 + JavaFX 14
I'm making a simple JavaFX calculator-style app, and using SceneBuilder.
Is there an easier way to reference the fields in a SceneBuilder-built app, other than referring to individual unique fx:id
's? For example, if I have a UI built in SceneBuilder that has some rows and columns of data:
---------------------
| field00 | field01 |
| field10 | field11 |
---------------------
and I want to do some math on the data. Is there an easier way to reference the fields other than referring to static names?
@FXML private TextField field00;
@FXML private TextField field01;
@FXML private TextField field10;
@FXML private TextField field11;
I'm doing what has to be super naive stuff like: if field00 is not null and if field01 is not null and ...
. I've made it a bit better by creating a class to represent each row and I'm reading those objects into an ArrayList, but my code to create the objects is still ugly stuff like:
RowList myRowList = new RowList();
MyRowClass aRow =
new MyRowClass(
Double.parseDouble(field00.getText()),
Double.parseDouble(field01.getText()));
myRowList.addRow(aRow);
aRow =
new Assignment(
Double.parseDouble(field10.getText()),
Double.parseDouble(field11.getText()));
myRowList.addRow(aRow);
I'd like to be able to iterate through the fields in some way.
Also, I'd like to add an "add a row" button to the UI and include that row in the calculations which would introduce some non-statically named fields to the mix.
Is the solution here to skip SceneBuilder and create the UI directly in my code?
Upvotes: 1
Views: 125
Reputation: 469
If you put the TextFields inside a container such as a HBox, you can use the .getChildren()
method on the container object to get all of its children nodes. You could then loop through all of them like this:
HBox h = new HBox();
h.getChildren().add(new TextField());
h.getChildren().add(new TextField());
h.getChildren().add(new TextField());
// loop through each node in the HBox
for (Node n : h.getChildren())
{
// if the Node is of type TextField, and the text inside is not null
if (n instanceof TextField && ((TextField) n).getText() != null)
{
// do something
}
}
Upvotes: 1