Why can't this css statement in Java FX2 code

2019-07-20 04:38发布

问题:

Statement 1 gets image file from css and fails to find the image file even though I supply an absolute url. Why?

The image file location is correct because in statement 3, it works. This is a further query of a solution posted by jewelsea.

import javafx.scene.image.Image;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class TextFieldCssSample extends Application {

    @Override
    public void start(Stage stage) {
        TextField textField = new TextField();
        textField.setId("textField");
        StackPane layout = new StackPane();
        layout.getChildren().addAll(textField);
        // 1) following statement **fails**. resources folder is below the root level folder
        textField.setStyle("-fx-border-color: red; -fx-background-image:url('/resources/pumpkin-icon.png'); -fx-background-repeat: no-repeat; -fx-background-position: right center;");
        // 2) following statement succeeds in finding a http url. 
        //    textField.setStyle("-fx-border-color: red; -fx-background-image:url('http://icons.iconarchive.com/icons/rockettheme/halloween/32/pumpkin-icon.png'); -fx-background-repeat: no-repeat; -fx-background-position: right center;");
        // 3) following statement succeeds finding image file. 
        stage.getIcons().add(new Image("/resources/pumpkin-icon.png"));
        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Update: cnahr's workaround worked! I have also opened a JavaFX bug report.RT-31131

回答1:

Omit the leading slash in the inline CSS URL.

Seriously. I just experimented a bit, and found that an image embedded in the JAR would load only when the complete URL was specified as a relative URL within an inline CSS like (1).

However, when I used an Image constructor as in (3) then I could either omit or include the leading slash. The image would load fine regardless.

So I think you just found a bug in the JavaFX CSS parser. :)


Note: RT-31131 Inline CSS statement in Java FX2 code can't find the image file when absolute path is used was closed as a duplicate of RT-21697 CSS: Absolute paths in url("...") without a scheme should be relative to the classpath, which was resolved for the Java 8 release, so the CSS processing error has been fixed in later JavaFX releases.



标签: javafx-2