将图形设置为标签

问题描述 投票:1回答:2

我想将Label设置为图形。我测试了这段代码:

    private static final ImageView livePerformIcon;

        static
        {
            livePerformIcon = new ImageView(MainApp.class.getResource("/images/Flex.jpg").toExternalForm());
        }

final Label label = new Label();
            label.setStyle("-fx-background-image: url(\"/images/Flex.jpg\");");

            livePerformIcon.setFitHeight(20);
            livePerformIcon.setFitWidth(20);
            label.setGraphic(livePerformIcon);

但我没有看到任何形象。

我发现让它发挥作用的唯一方法是:

label.setStyle("-fx-background-image: url(\"/images/Flex.jpg\");");

有办法解决这个问题吗?

javafx javafx-2 javafx-8
2个回答
1
投票

不确定,但是应该在JavaFX Application线程上创建AFAIK控件,但是你在静态初始化器中创建了ImageView,我不确定它是否在Application线程上执行。

另外:你真的希望livePerformIcon是静态的???


1
投票

这个由文档中使用的数据制成,对我来说非常适合

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class LabelWithImages extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group());
    stage.setTitle("Label With Image Sample");
    stage.setWidth(400);
    stage.setHeight(180);

    HBox hbox = new HBox();
    //Replace the image you want to put up
    Image image = new Image(getClass().getResourceAsStream("a.png"));
    Label label = new Label("Demo Label");
    label.setGraphic(new ImageView(image));
    hbox.setSpacing(10);
    hbox.getChildren().add((label));
    ((Group) scene.getRoot()).getChildren().add(hbox);

    stage.setScene(scene);
    stage.show();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.