Answer the question
In order to leave comments, you need to log in
How to put custom fonts in combobox in JavaFX?
There is a label with text and a combobox in the application. When I click on the combobox, a list of fonts pops up. When you click on a font, the font of the label text changes to the selected one. At the moment, my combobox is working fine, but only fonts that are installed in the system (WIndows / fonts) are displayed there, but I need only fonts from the folder located in the program folder to be displayed in the combobox.
System - Windows 10
How to display my custom fonts in combobox?
If it is not possible to put your custom fonts from the program folder in the combobox, is it possible to change the path to the system folder with fonts?
@FXML private ComboBox<Font> fontSelector;
@FXML private Label fontLabel;
//get font family and size
private static Font getFont(Font font, Integer size) {
return Font.font(font == null ? null : font.getFamily(), size == null ? -1d : size.doubleValue());
}
//add font families to combboox
fontSelector.getItems().addAll(Font.getFamilies().stream().map(name -> Font.font(name, 14)).toArray(Font[]::new));
// bind font based on size/family
fontLabel.fontProperty()
.bind(Bindings.createObjectBinding(() -> getFont(fontSelector.getValue(), size.getValue()),
fontSelector.valueProperty(), size.valueProperty()));
//display and render font families looks in combobox
class FontListCell extends ListCell<Font> {
@Override
public void updateItem(Font item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.getFamily());
setFont(item);
} else {
setText("");
setFont(Font.font(12));
}
}
}
fontSelector.setCellFactory(lv -> new FontListCell());
fontSelector.setButtonCell(new FontListCell());
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question