我想将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\");");
有没有办法解决这个问题?
答案 0 :(得分:1)
不确定,但是应该在JavaFX Application线程上创建AFAIK控件,但是你在静态初始化器中创建了ImageView,我不确定它是否在Application线程上执行。
此外:你真的希望livePerformIcon是静态的吗?
答案 1 :(得分: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();
}
}
答案 2 :(得分:0)
代码段将设置标签属性图形的值。您可以使用两者中的任何一个。我更喜欢使用javafx css来实现model-view-controller设计。
// programmatically, provided with image input stream
label.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("path/to/image.png"))));
// javafx css, provided with image url
.label {
-fx-graphic: url("path/to/image.png");
}