drewpol drewpol - 18 days ago 6
Java Question

Updating text font in combobox in javafx

I have a part of the code. I want to show all fonts, which I have on my OS in combo box. Then names of fonts should look like a preview showing how each font looks. This is my code :

List<String> families = Font.getFamilies();
fontfamilies = FXCollections.observableArrayList(families);
comboBox.setItems(fontfamilies);
comboBox.getSelectionModel().select(0);

comboBox.setCellFactory((ListView<String> listView) -> {
final ListCell<String> cell = new ListCell<String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item);
setFont(new Font(item, 12));
}
}
};
//cell.setPrefWidth(120);
return cell;
});


But I get this error:

Error:(59, 20) java: incompatible types: bad return type in lambda expression
javafx.scene.control.ListCell<java.lang.String> cannot be converted to javafx.scene.control.ListCell<capture#1 of ?>


Can anyone help me with this issue ?

Answer

Your problem is related to how you defined your member variable comboBox, you defined it using wildcard which represents an unknown type while the rest of your code expect String as ComboBox's type.

So simply define it as next:

@FXML private ComboBox<String> comboBox;
Comments