Improved language combobox

This commit is contained in:
Jeddunk 2020-08-28 18:32:39 +02:00
parent 308f20cb81
commit 8c23ae27e8

View File

@ -16,9 +16,13 @@
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
@ -44,6 +48,7 @@ import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.stream.Stream;
public class Controller {
@ -109,6 +114,9 @@ public class Controller {
public void initialize() {
appId_textfield.textProperty().addListener(appIdChangesGameName());
language_combobox.setItems(FXCollections.observableArrayList(config.getLanguages()));
language_combobox.setTooltip(new Tooltip());
language_combobox.setEditable(false);
new ComboBoxAutoComplete<>(language_combobox);
//retrieveDlcList_button.setDisable(true); // WIP
generate_tooltips();
fix_dlc_textarea_prompt_text();
@ -442,4 +450,62 @@ public class Controller {
public void resetFromButton() {
reset(false);
}
static class ComboBoxAutoComplete<T> {
private ComboBox<T> cmb;
String filter = "";
private ObservableList<T> originalItems;
public ComboBoxAutoComplete(ComboBox<T> cmb) {
this.cmb = cmb;
originalItems = FXCollections.observableArrayList(cmb.getItems());
cmb.setTooltip(new Tooltip());
cmb.setOnKeyPressed(this::handleOnKeyPressed);
cmb.setOnHidden(this::handleOnHiding);
}
public void handleOnKeyPressed(KeyEvent e) {
SingleSelectionModel<T> sm = this.cmb.getSelectionModel();
ObservableList<T> filteredList = FXCollections.observableArrayList();
KeyCode code = e.getCode();
if (code.isLetterKey()) {
filter += e.getText();
}
if (code == KeyCode.BACK_SPACE && filter.length() > 0) {
filter = filter.substring(0, filter.length() - 1);
cmb.getItems().setAll(originalItems);
}
if (code == KeyCode.ESCAPE) {
filter = "";
}
if (filter.length() == 0) {
filteredList = originalItems;
cmb.getTooltip().hide();
} else {
Stream<T> items = cmb.getItems().stream();
String txtUsr = filter.toLowerCase();
items.filter(el -> el.toString().toLowerCase().contains(txtUsr)).forEach(filteredList::add);
cmb.getTooltip().setText(txtUsr);
Window stage = cmb.getScene().getWindow();
double posX = stage.getX() + cmb.getBoundsInParent().getMinX();
double posY = stage.getY() + cmb.getBoundsInParent().getMinY();
cmb.getTooltip().show(stage, posX, posY);
cmb.show();
}
cmb.getItems().setAll(filteredList);
sm.selectFirst();
}
public void handleOnHiding(Event e) {
filter = "";
cmb.getTooltip().hide();
T s = cmb.getSelectionModel().getSelectedItem();
cmb.getItems().setAll(originalItems);
cmb.getSelectionModel().select(s);
}
}
}