Issue
I have a basic question for JavaFX but coudn't figure it out. For HBox, When I'm using getChildren().addAll() for Label and ImageView, I get the following message:
The method addAll(int, Collection<? extends Node>) in the type List<Node> is not applicable for the argument (Label, ImageView[])
I'm not sure what's the issue. I can use normally if its (TextField, ImageView[]), but it doesn't work for (Label, ImageView[]).
This is my simplified code:
ImageView[] imagesRow = new ImageView[2];
Image[] img = new Image[2];
String title = "Result";
img[0] = new Image("sample1.png", 60, 35, true, true);
img[1] = new Image("sample2.png", 60, 35, true, true);
imagesRow[0] = new ImageView();
imagesRow[1] = new ImageView();
imagesRow[0].setImage (img[0]);
imagesRow[1].setImage (img[1]);
Label label = new Label();
label.setText(title + ": ");
// Create horizontal box
HBox box = new HBox();
box.setPadding(new Insets(20, 5 , 2, 50));
box.getChildren().addAll(label, imagesRow); // issue here
May I seek the reason and what should I do instead to align label and image horizontally? Thanks in advance.
Solution
A Collection
needs to be of one type (or inheriting from a common parent somewhere in the heirarchy).
A Label
is a type of Node
and therefore anything else you try to pass as a part of the Collection
parameter must also be a Node
. An array is obviously not.
In your case, you would need to use two calls to populate the children of the HBox
:
box.getChildren().add(label);
box.getChildren().addAll(imagesRow);
The reason you can call addAll(imagesRow)
without a problem is because with only the one argument, you're only passing in one Collection
, an array.
By calling addAll(label, imagesRow)
, you're telling Java that you're passing a Collection
of one type, but you actually passed it a Node
and an array.
Answered By - Zephyr
Answer Checked By - Katrina (JavaFixing Volunteer)