0

我想在窗格中添加两个不同的带有图像的标签。我使用的代码是这样的:

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);


    }



}

我的问题是它没有在屏幕上添加两个标签。

如果我有:

this.getChildren().add(label1);
this.getChildren().add(label2);

它在屏幕上只显示标签 2,即使我 print(this.getchildren()) 它有两个标签。

如果我有其中之一,它会正常添加。

即使我两者都没有并执行

this.getChildren().addAll(label1, label2);

它仍然只添加标签2。

这是为什么?

谢谢

4

2 回答 2

4

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

于 2013-04-09T13:07:05.437 回答
1

这是因为 ImageView 是一个节点,它不能在 Scenegraph 中出现两次。添加第二个 ImageView 并将其添加到第二个标签。

private ImageView image1 = new ImageView(new Image(getClass().getResourceAsStream("red.jpg")));

于 2013-04-09T13:01:47.630 回答