50 lines
1.4 KiB
Java
50 lines
1.4 KiB
Java
package io.gitlab.jfronny.inceptum.gtk.control;
|
|
|
|
import io.gitlab.jfronny.commons.throwable.ThrowingRunnable;
|
|
import io.gitlab.jfronny.inceptum.gtk.menu.MenuBuilder;
|
|
import org.gtk.gtk.MenuButton;
|
|
|
|
import java.util.LinkedList;
|
|
import java.util.List;
|
|
import java.util.function.*;
|
|
|
|
public class Dropdown<T> extends MenuButton {
|
|
private final T[] source;
|
|
private final List<Consumer<T>> onChange = new LinkedList<>();
|
|
private int selected;
|
|
|
|
public Dropdown(T[] source, int def, Function<T, String> stringify) {
|
|
this.source = source;
|
|
MenuBuilder builder = MenuBuilder.create(this, "nil");
|
|
this.selected = def;
|
|
for (int i = 0; i < source.length; i++) {
|
|
String n = stringify.apply(source[i]);
|
|
if (def == i) label = n;
|
|
builder.literalButton("" + i, n, new LB(i, n));
|
|
}
|
|
}
|
|
|
|
public void onChanged(Consumer<T> action) {
|
|
onChange.add(action);
|
|
}
|
|
|
|
private class LB implements ThrowingRunnable<RuntimeException> {
|
|
private final int i;
|
|
private final String n;
|
|
|
|
public LB(int i, String n) {
|
|
this.i = i;
|
|
this.n = n;
|
|
}
|
|
|
|
@Override
|
|
public void run() throws RuntimeException {
|
|
if (selected != i) {
|
|
selected = i;
|
|
for (Consumer<T> action : onChange) action.accept(source[i]);
|
|
Dropdown.this.label = n;
|
|
}
|
|
}
|
|
}
|
|
}
|