Monday, February 25, 2013

Example to apply font

This example demonstrate how to apply the selected font family on Label. Also demonstrate how to use JavaFX SplitPane.

Example to apply font
Example to apply font


package javafxfonts;

import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFXFonts extends Application {

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("http://java-buddy.blogspot.com/");

StackPane sp2 = new StackPane();
final Label label = new Label();
sp2.getChildren().add(label);

final ListView<String> listView = new ListView<>();
List<String> familiesList = Font.getFamilies();
ObservableList<String> familiesObservableList =
FXCollections.observableArrayList(familiesList);
listView.setItems(familiesObservableList);

listView.setOnMouseClicked(new EventHandler<MouseEvent>(){

@Override
public void handle(MouseEvent t) {
String selectedFamily =
listView.getSelectionModel().getSelectedItem();

//Apply the selected font family
Font selectedFont = Font.font(selectedFamily, 20.0);
label.setText(selectedFamily);
label.setFont(selectedFont);
}
});

SplitPane splitPane = new SplitPane();
StackPane sp1 = new StackPane();
sp1.getChildren().add(listView);

splitPane.getItems().addAll(sp1, sp2);

primaryStage.setScene(new Scene(splitPane, 300, 250));
primaryStage.show();

}

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


Related article: Load True Type Font (ttf) in JavaFX

No comments:

Post a Comment