JavaFX Tip 12: Define Icons in CSS
When you are a UI developer coming from Swing like me then there is a good chance that you are still setting images / icons directly in your code. Most likely something like this:
import javafx.scene.control.Label; import javafx.scene.image.ImageView; public class MyLabel extends Label { public MyLabel() { setGraphic(new ImageView(MyLabel.class. getResource("image.gif").toExternalForm())); } }
In this example the image file is looked up via Class.getResource(), the URL is passed to the constructor of the ImageView node and this node is set as the “graphic” property on the label.
This approach works perfectly well but with JavaFX there is a more elegant way. You can put the image definition into a CSS file, making it easy for you and / or others to replace it (the marketing department has decided to change the corporate identity once again).
The same result as above can be achieved this way:
import javafx.scene.control.Label; public class CSSLabel extends Label { public CSSLabel() { getStyleClass().add("folder-icon"); } }
Now you obviously need a CSS file as well:
.folder-icon { -fx-graphic: url("image.gif"); }
And in your application you need to add the stylesheet to your scene graph. Here we are adding it to the scene.
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.stage.Stage; public class MyApplication extends Application { public void start(Stage primaryStage) throws Exception { CSSLabel label = new CSSLabel(); label.setText("Folder"); label.setAlignment(Pos.CENTER); Scene scene = new Scene(label); scene.getStylesheets().add(MyApplication.class. getResource("test.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setTitle("Image Example"); primaryStage.setWidth(250); primaryStage.setHeight(100); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
With this approach you have a clean separation of your controls and their apperance and you allow for easy customization as well.
Reference: | JavaFX Tip 12: Define Icons in CSS from our JCG partner Dirk Lemmermann at the Pixel Perfect blog. |