Skip to content

Instantly share code, notes, and snippets.

@jewelsea
Created March 13, 2012 22:29
Show Gist options
  • Save jewelsea/2032230 to your computer and use it in GitHub Desktop.
Save jewelsea/2032230 to your computer and use it in GitHub Desktop.
CustomFontExample.java
import java.util.Iterator;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.Window;
public class CustomFontExample extends Application {
public static void main(String[] args) { launch(args); }
@Override public void start(Stage stage) {
stage.setTitle("TRON Synopsis");
// create a menu.
final MenuItem openMenuItem = new MenuItem("Open");
final Menu fileMenu = new Menu("File");
fileMenu.getItems().add(openMenuItem);
final MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(fileMenu);
// display a title using a custom font.
final Font titleFont = Font.loadFont(CustomFontExample.class.getResource("TRON.TTF").toExternalForm(), 20);
final Label title = new Label("TRON");
title.setWrapText(true);
title.setFont(titleFont);
// movie poster.
final ImageView image = new ImageView("http://ia.media-imdb.com/images/M/MV5BMTY5NjM2MjAwOV5BMl5BanBnXkFtZTYwMTgyMzA5.V1.SY317.jpg");
// movie poster caption in a smaller font.
final Font smallFont = Font.loadFont(CustomFontExample.class.getResource("TRON.TTF").toExternalForm(), 10);
final Label caption = new Label("A sci-fi flick set in an alternate reality.");
caption.setWrapText(true);
caption.setFont(smallFont);
// layout the scene.
final VBox layout = new VBox(10); layout.getChildren().addAll(menuBar, title, image, caption);
layout.setAlignment(Pos.CENTER);
layout.setStyle("-fx-background-color: linear-gradient(to bottom, silver, derive(silver, 80%));");
final Scene scene = new Scene(layout, 400, 600);
stage.setScene(scene);
stage.show();
// set the font for the menu items to the small custom font.
// note use of deprecated impl_ method, a public API should be used instead if possible.
setFontForLabelsUnder(menuBar, smallFont);
fileMenu.setOnShown(new EventHandler<Event>() {
@Override public void handle(Event event) {
Iterator<Window> windows = Stage.impl_getWindows();
while (windows.hasNext()) {
Window next = windows.next();
if (next instanceof ContextMenu) {
setFontForLabelsUnder(((ContextMenu) next).getScene().getRoot(), smallFont);
}
}
}
});
}
private void setFontForLabelsUnder(Node parent, Font customFont) {
for (Node n: parent.lookupAll(".label")) {
if (n instanceof Label) {
((Label) n).setFont(customFont);
}
}
}
}
@jewelsea
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment