Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javafx.application.Application;
- import javafx.beans.property.SimpleBooleanProperty;
- import javafx.beans.property.SimpleStringProperty;
- import javafx.beans.property.StringProperty;
- import javafx.collections.FXCollections;
- import javafx.collections.ObservableList;
- import javafx.scene.Scene;
- import javafx.scene.control.ComboBox;
- import javafx.scene.control.TableView;
- import javafx.stage.Stage;
- import javafx.util.StringConverter;
- public class ComboBoxDemo extends Application{
- public class SimplePerson {
- private StringProperty name;
- private String somethingElse;
- public SimplePerson(String name) {
- setName(name);
- }
- public final void setName(String value) { nameProperty().set(value); }
- public String getName() { return nameProperty().get(); }
- public StringProperty nameProperty() {
- if (name == null) name = new SimpleStringProperty(this, "name");
- return name;
- }
- }
- final ObservableList<SimplePerson> persons = FXCollections.observableArrayList(
- new SimplePerson("Jacob"),
- new SimplePerson("Isabella"),
- new SimplePerson("Ethan"),
- new SimplePerson("Emma"),
- new SimplePerson("Michael")
- );
- @Override
- public void start(Stage stage) throws Exception {
- final ComboBox<SimplePerson> cb = new ComboBox<>();
- cb.setItems(persons);
- cb.setEditable(true);
- cb.setConverter(new StringConverter<SimplePerson>() {
- @Override
- public String toString(SimplePerson p)
- {
- if(p != null)
- return p.getName();
- return "";
- }
- @Override
- public SimplePerson fromString(String name)
- {
- if(cb.getValue() != null)
- {
- ((SimplePerson)cb.getValue()).setName(name);
- cb.show();
- return (SimplePerson)cb.getValue();
- }
- return null;
- }
- });
- cb.getEditor().setOnAction(e -> {
- SimplePerson person = cb.getSelectionModel().getSelectedItem();
- if (null != person) {
- person.setName(cb.getEditor().getText());
- } else {
- SimplePerson p = new SimplePerson(cb.getEditor().getText());
- cb.getItems().add(p);
- cb.getSelectionModel().select(p);
- }
- });
- stage.setScene(new Scene(cb));
- stage.show();
- }
- public static void main(String[] args) { launch(args); }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement