I use JavaFX and Scene Builder
There is a label, and a combobox with fonts. When choosing a font from a combobox, it is applied to the label. Work then the combobox works but is bad
1.When clicking on a combobox, the list of fonts does not open immediately, but after a second, as if the combobox is slowing down.
2.When the first font is selected, it is not applied to the label, and the use of the font only works if I click on the combobox again and select the font again, and not the one that was active.
How can you optimize the code so that everything works like a clock?
Maybe I did the wrong implementation of applying the font to the label.
@FXML private ComboBox<String> fontSelector; @FXML private Label fontLabel; When clicking on the combobox, the method is called:
public void changeLabel(ActionEvent event) { //apply selected font from combobox to label fontSelector.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> fontLabel.setFont(Font.font(newValue, FontWeight.NORMAL, 35))); } //get system fonts ObservableList<String> fonts = FXCollections.observableArrayList(Font.getFamilies()); Further:
@Override public void initialize(URL location, ResourceBundle resources) { //show fonts' actual look in combobox list fontSelector.setCellFactory((ListView<String> listView) -> { final ListCell<String> cell = new ListCell<>(){ @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (item != null) { setText(item); setFont(new Font(item, 14)); } } }; return cell; }); fontSelector.setItems(fonts); } Editorial:
I changed the method that shows the system fonts in the combobox, but when I click on the combobox, the delay per second is still
@FXML private ComboBox<Font> fontSelector; //get font family and size from comboboxes private static Font getFont(Font font, Integer size) { return Font.font(font == null ? null : font.getFamily(), size == null ? -1d : size.doubleValue()); } //getting font families 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 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()); } EDITOR 2:
I forgot to write that the problem is precisely in the display of the font family, that is, the names of the fonts, and not the font sizes.