Reputation: 163
I want to add two different labels with image in Pane. The code I use is this:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Controller extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Starting FX");
primaryStage.setScene(new Scene(new Panel(), 590, 390));
primaryStage.setResizable(false);
primaryStage.centerOnScreen();
primaryStage.show();
}
}
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
public class Panel extends Pane {
private ImageView image = new ImageView(new Image(getClass().getResourceAsStream("red.jpg")));
private Label label1 = new Label();
private Label label2 = new Label();
public Panel() {
label1.relocate(524, 280);
label1.setGraphic(image);
this.getChildren().add(label1);
label2.relocate(250, 200);
label2.setGraphic(image);
this.getChildren().add(label2);
}
}
My problem is that it doesn't add both labels on screen.
If I have:
this.getChildren().add(label1);
this.getChildren().add(label2);
it shows only label 2 on screen, even though if I print(this.getchildren()) it has both labels.
If I have one of them, it adds it normally.
Even if I don't have neither and execute
this.getChildren().addAll(label1, label2);
still it adds only label2.
Why is that?
Thank you
Upvotes: 0
Views: 9973
Reputation: 1938
Both Labels are actually there but they can't both use the same ImageView in the scenegraph. If you add text to the Labels you should see them. You'll have to create two separate ImageView instances, one for each label. Try this.
public class Panel extends Pane
{
Image labelImage = new Image(getClass().getResourceAsStream("red.jpg"));
private Label label1 = new Label();
private Label label2 = new Label();
public Panel()
{
label1.relocate(524, 280);
label1.setGraphic(new ImageView(labelImage));
this.getChildren().add(label1);
label2.relocate(250, 200);
label2.setGraphic(new ImageView(labelImage));
this.getChildren().add(label2);
}
}
Checkout this post for more info Reusing same ImageView multiple times in the same scene on JavaFX
Upvotes: 4
Reputation: 540
It's because the ImageView is a node and it can't be twice in the Scenegraph. Add a second ImageView and add this to the second label.
private ImageView image1 = new ImageView(new Image(getClass().getResourceAsStream("red.jpg")));
Upvotes: 1