Java Code Examples for javafx.collections.ObservableList#addListener()

The following examples show how to use javafx.collections.ObservableList#addListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WarListController.java    From VickyWarAnalyzer with MIT License 6 votes vote down vote up
public void init(MainController mainController, ModelService model, Tab tab) {
	main = mainController;
	modelServ = model;
	this.tab = tab;
	warTableContent = FXCollections.observableArrayList();

	selectCountryIssue.getSelectionModel().selectedItemProperty()
			.addListener((arg0, arg1, arg2) -> {
				warTableShowCountry(arg2.getTag());
			});
	/* Listening to selections in warTable */
	final ObservableList<War> warTableSelection =
			warTable.getSelectionModel().getSelectedItems();
	warTableSelection.addListener(tableSelectionChanged);

	warTable.setItems(warTableContent);
	setColumnValues();
}
 
Example 2
Source File: EasyBind.java    From EasyBind with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Sync the content of the {@code target} list with the {@code source} list.
 * @return a subscription that can be used to stop syncing the lists.
 */
public static <T> Subscription listBind(
        List<? super T> target,
        ObservableList<? extends T> source) {
    target.clear();
    target.addAll(source);
    ListChangeListener<? super T> listener = change -> {
        while(change.next()) {
            int from = change.getFrom();
            int to = change.getTo();
            if(change.wasPermutated()) {
                target.subList(from, to).clear();
                target.addAll(from, source.subList(from, to));
            } else {
                target.subList(from, from + change.getRemovedSize()).clear();
                target.addAll(from, source.subList(from, from + change.getAddedSize()));
            }
        }
    };
    source.addListener(listener);
    return () -> source.removeListener(listener);
}
 
Example 3
Source File: CSSFXMonitor.java    From scenic-view with GNU General Public License v3.0 6 votes vote down vote up
private void monitorStages(ObservableList<? extends Window> observableStages) {
    // first listen for changes
    observableStages.addListener(new ListChangeListener<Window>() {
        @Override
        public void onChanged(javafx.collections.ListChangeListener.Change<? extends Window> c) {
            while (c.next()) {
                if (c.wasRemoved()) {
                    for (Window removedStage : c.getRemoved()) {
                        unregisterStage(removedStage);
                    }
                }
                if (c.wasAdded()) {
                    for (Window addedStage : c.getAddedSubList()) {
                        registerStage(addedStage);
                    }
                }
            }
        }
    });

    // then process already existing stages
    for (Window stage : observableStages) {
        registerStage(stage);
    }

}
 
Example 4
Source File: CSSFXMonitor.java    From scenic-view with GNU General Public License v3.0 6 votes vote down vote up
private void monitorScenes(ObservableList<Scene> observableScenes) {
    // first listen for changes
    observableScenes.addListener(new ListChangeListener<Scene>() {
        @Override
        public void onChanged(javafx.collections.ListChangeListener.Change<? extends Scene> c) {
            while (c.next()) {
                if (c.wasRemoved()) {
                    for (Scene removedScene : c.getRemoved()) {
                        unregisterScene(removedScene);
                    }
                }
                if (c.wasAdded()) {
                    for (Scene addedScene : c.getAddedSubList()) {
                        registerScene(addedScene);
                    }
                }
            }
        }
    });
    
    // then add existing values
    for (Scene s : observableScenes) {
        registerScene(s);
    }
}
 
Example 5
Source File: Tools.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * テーブルソート列の設定を行う
 * @param table テーブル
 * @param key テーブルのキー名
 */
public static <S> void setSortOrder(TableView<S> table, String key) {
    Map<String, String> setting = AppConfig.get()
            .getColumnSortOrderMap()
            .get(key);
    ObservableList<TableColumn<S, ?>> sortOrder = table.getSortOrder();
    if (setting != null) {
        // 初期設定
        Map<String, TableColumn<S, ?>> columnsMap = getColumns(table)
                .collect(Collectors.toMap(Tables::getColumnName, c -> c, (c1, c2) -> c1));
        setting.forEach((k, v) -> {
            Optional.ofNullable(columnsMap.get(k)).ifPresent(col -> {
                sortOrder.add(col);
                col.setSortType(SortType.valueOf(v));
            });
        });
    }
    // ソート列またはソートタイプが変更された時に設定を保存する
    sortOrder.addListener((ListChangeListener<TableColumn<S, ?>>) e -> storeSortOrder(table, key));
    getColumns(table).forEach(col -> {
        col.sortTypeProperty().addListener((ob, o, n) -> storeSortOrder(table, key));
    });
}
 
Example 6
Source File: CSSFXMonitor.java    From cssfx with Apache License 2.0 6 votes vote down vote up
public void monitorStylesheets(ObservableList<String> stylesheets) {
    final URIRegistrar registrar = new URIRegistrar(knownConverters, pw);

    // first register for changes
    stylesheets.addListener(new StyleSheetChangeListener(registrar));

    // then look already set stylesheets uris
    // iterate over a copy to avoid concurrent modification
    ArrayList<String> stylesheetsURI = new ArrayList<>(stylesheets);
    for (String uri : stylesheetsURI) {
        registrar.register(uri, stylesheets);
    }

    CleanupDetector.onCleanup(stylesheets, () -> {
        Platform.runLater(() -> {
            // This is important, so no empty "Runnables" build up in the PathsWatcher
            registrar.cleanup();
        });
    });
}
 
Example 7
Source File: DescriptiveStatisticsTimelineView.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
public DescriptiveStatisticsTimelineView(final ObservableList<Double> scores) {
	super(new NumberAxis(), new NumberAxis());

	// defining the axes
	this.getXAxis().setLabel("elapsed time (s)");

	// defining a series
	this.scores = scores;
	this.performanceSeries = new Series<>();
	this.getData().add(this.performanceSeries);
	this.update();
	scores.addListener(new ListChangeListener<Double>() {

		@Override
		public void onChanged(final Change<? extends Double> c) {
			DescriptiveStatisticsTimelineView.this.update();
		}
	});
}
 
Example 8
Source File: WorkbenchUtils.java    From WorkbenchFX with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a {@link ListChangeListener} to an {@link ObservableList}.
 *
 * @param list to add a listener to
 * @param addAction action to be performed when an object was added to the {@link ObservableList}
 * @param removeAction action to be performed when an object was removed
 *                     from the {@link ObservableList}
 * @param <T> type of the {@link ObservableList}
 */
public static <T> void addListListener(ObservableList<T> list,
    Consumer<T> addAction,
    Consumer<T> removeAction) {
  list.addListener((ListChangeListener<? super T>) c -> {
    while (c.next()) {
      if (!c.wasPermutated() && !c.wasUpdated()) {
        for (T remitem : c.getRemoved()) {
          removeAction.accept(remitem);
        }
        for (T additem : c.getAddedSubList()) {
          addAction.accept(additem);
        }
      }
    }
  });
}
 
Example 9
Source File: CSSFXMonitor.java    From cssfx with Apache License 2.0 6 votes vote down vote up
private void monitorWindows(ObservableList<? extends Window> observableWindows) {
    // first listen for changes
    observableWindows.addListener(new ListChangeListener<Window>() {
        @Override
        public void onChanged(javafx.collections.ListChangeListener.Change<? extends Window> c) {
            while (c.next()) {
                if (c.wasRemoved()) {
                    for (Window removedWindow : c.getRemoved()) {
                        unregisterWindow(removedWindow);
                    }
                }
                if (c.wasAdded()) {
                    for (Window addedWindow : c.getAddedSubList()) {
                        registerWindow(addedWindow);
                    }
                }
            }
        }
    });

    // then process already existing stages
    for (Window stage : observableWindows) {
        registerWindow(stage);
    }

}
 
Example 10
Source File: TopicPropertiesWindow.java    From kafka-message-tool with MIT License 5 votes vote down vote up
private TopicPropertiesWindow(ObservableList<TopicsOffsetInfo> topicOffsetsInfo) throws IOException {

        observablesOffsetsFromCaller = topicOffsetsInfo;

        loadAnchorPane(this, FXML_FILE);
        configureTable();


        topicOffsetsInfo.addListener(new ListChangeListener<TopicsOffsetInfo>() {
            @Override
            public void onChanged(Change<? extends TopicsOffsetInfo> c) {
                refresh(topicName, entriesView, observablesOffsetsFromCaller);
            }
        });
    }
 
Example 11
Source File: PopupSelectboxContainer.java    From logbook-kai with MIT License 5 votes vote down vote up
void init() {
    ObservableList<T> items = this.items.get();
    if (items != null) {
        items.addListener(this::reset);
        this.page.setPageCount((int) Math.max(Math.ceil(((double) items.size()) / this.maxPageItem.get()), 1));
    }
    this.page.setPageFactory(new PageFactory());
    this.page.setMaxPageIndicatorCount(7);
}
 
Example 12
Source File: EventStreams.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @see LiveList#changesOf(ObservableList)
 */
public static <T> EventStream<ListChangeListener.Change<? extends T>> changesOf(ObservableList<T> list) {
    return new EventStreamBase<ListChangeListener.Change<? extends T>>() {
        @Override
        protected Subscription observeInputs() {
            ListChangeListener<T> listener = c -> emit(c);
            list.addListener(listener);
            return () -> list.removeListener(listener);
        }
    };
}
 
Example 13
Source File: SeqTraceView.java    From erlyberly with GNU General Public License v3.0 5 votes vote down vote up
public SeqTraceView(ObservableList<SeqTraceLog> seqTraceLogs) {
    table = new TableView<SeqTraceLog>();
    table.setOnMouseClicked(this::onTraceClicked);
    table.setMaxHeight(Integer.MAX_VALUE);
    VBox.setVgrow(table, Priority.ALWAYS);

    setupTableColumns();

    getChildren().add(table);

    seqTraceLogs.addListener(this::traceLogsChanged);
}
 
Example 14
Source File: CSSFXMonitor.java    From scenic-view with GNU General Public License v3.0 5 votes vote down vote up
private void monitorStylesheets(Object origin, ObservableList<String> stylesheets) {
    // first register for changes
    stylesheets.addListener(new StyleSheetChangeListener(registrar, origin));

    // then look already set stylesheets uris
    for (String uri : stylesheets) {
        // we register the stylesheet only if it is not one that CSSFX added in replacement of a monitored one
        if (!isAManagedSourceURI(uri)) {
            registrar.register(origin, uri, stylesheets);
        }
    }
}
 
Example 15
Source File: LiveList.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static <E> Subscription observeQuasiChanges(
        ObservableList<? extends E> list,
        QuasiChangeObserver<? super E> observer) {
    if(list instanceof LiveList) {
        LiveList<? extends E> lst = (LiveList<? extends E>) list;
        return lst.observeQuasiChanges(observer);
    } else {
        ListChangeListener<E> listener = ch -> {
            QuasiListChange<? extends E> change = QuasiListChange.from(ch);
            observer.onChange(change);
        };
        list.addListener(listener);
        return () -> list.removeListener(listener);
    }
}
 
Example 16
Source File: TreeViewDemo.java    From JFoenix with Apache License 2.0 5 votes vote down vote up
protected void setHiddenFieldChildren(ObservableList<TreeItem<T>> list) {
    try {
        Field childrenField = TreeItem.class.getDeclaredField("children"); //$NON-NLS-1$
        childrenField.setAccessible(true);
        childrenField.set(this, list);

        Field declaredField = TreeItem.class.getDeclaredField("childrenListener"); //$NON-NLS-1$
        declaredField.setAccessible(true);
        list.addListener((ListChangeListener<? super TreeItem<T>>) declaredField.get(this));
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        throw new RuntimeException("Could not set TreeItem.children", e); //$NON-NLS-1$
    }
}
 
Example 17
Source File: HeadlessController.java    From ShootOFF with GNU General Public License v3.0 4 votes vote down vote up
public HeadlessController() {
	config = Configuration.getConfig();

	// Configuring cameras may cause us to bail out before doing anything
	// actually useful but we initialize these points first so that we can
	// make more fields immutable (initializing them after a guarded return
	// will make it so the can't be final unless we initialize them all to
	// null).
	final ObservableList<ShotEntry> shotEntries = FXCollections.observableArrayList();

	shotEntries.addListener(new ListChangeListener<ShotEntry>() {
		@Override
		public void onChanged(Change<? extends ShotEntry> change) {
			if (!server.isPresent() || !change.next() || change.getAddedSize() < 1) return;

			for (ShotEntry entry : change.getAddedSubList()) {
				final Shot shot = entry.getShot();
				final Dimension2D d = arenaPane.getArenaStageResolution();
				server.get().sendMessage(new NewShotMessage(shot.getColor(), shot.getX(), shot.getY(),
						shot.getTimestamp(), d.getWidth(), d.getHeight()));
			}
		}
	});

	final CanvasManager canvasManager = new CanvasManager(new Group(), this, "Default", shotEntries);

	final Stage arenaStage = new Stage();
	// TODO: Pass controls added to this pane to the device controlling
	// SBC
	final Pane trainingExerciseContainer = new Pane();

	arenaPane = new ProjectorArenaPane(arenaStage, null, trainingExerciseContainer, this, shotEntries);
	arenaCanvasManager = arenaPane.getCanvasManager();

	arenaStage.setTitle("Projector Arena");
	arenaStage.setScene(new Scene(arenaPane));
	arenaStage.setFullScreenExitHint("");

	camerasSupervisor = new CamerasSupervisor(config);

	final Map<String, Camera> configuredCameras = config.getWebcams();
	final Optional<Camera> camera;

	if (configuredCameras.isEmpty()) {
		camera = CameraFactory.getDefault();
	} else {
		camera = Optional.of(configuredCameras.values().iterator().next());
	}

	if (!camera.isPresent()) {
		logger.error("There are no cameras attached to the computer.");
		return;
	}

	final Camera c = camera.get();

	if (c.isLocked() && !c.isOpen()) {
		logger.error("Default camera is locked, cannot proceed");
		return;
	}

	initializePluginEngine();

	final Optional<CameraManager> manager = camerasSupervisor.addCameraManager(c, this, canvasManager);
	if (manager.isPresent()) {
		final CameraManager cameraManager = manager.get();

		// TODO: Camera views to non-null value to handle calibration issues
		calibrationManager = new CalibrationManager(this, cameraManager, arenaPane, null, this, this);

		arenaPane.setCalibrationManager(calibrationManager);
		arenaPane.toggleArena();
		arenaPane.autoPlaceArena();

		calibrationManager.enableCalibration();
	} else {
		logger.error("Failed to start camera {}", c.getName());
	}
}
 
Example 18
Source File: ProjectsComboBox.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 4 votes vote down vote up
ProjectsComboBox(FileEditorManager fileEditorManager) {
	getStyleClass().add("projects-combo-box");
	setFocusTraversable(false);
	setVisibleRowCount(30);
	setButtonCell(new ProjectButtonCell());
	setCellFactory(listView -> new ProjectListCell());

	// let this control grow horizontally
	setMaxWidth(Double.MAX_VALUE);

	// update tooltip
	valueProperty().addListener((observer, oldProject, newProject) -> {
		setTooltip((newProject != null) ? new Tooltip(newProject.getAbsolutePath()) : null);
	});

	// add items
	ObservableList<File> projects = ProjectManager.getProjects();
	projects.sort(PROJECT_COMPARATOR);
	getItems().add(OPEN_FOLDER);
	getItems().addAll(projects);

	// set active project
	setValue(ProjectManager.getActiveProject());

	// listen to selection changes
	getSelectionModel().selectedItemProperty().addListener((observer, oldProject, newProject) -> {
		if (inSelectionChange)
			return;

		if (newProject == ProjectManager.getActiveProject())
			return;

		Platform.runLater(() -> {
			inSelectionChange = true;
			try {
				if (newProject == OPEN_FOLDER) {
					// closing last active project automatically selects this item
					// --> activate first project
					if (oldProject != null && !getItems().contains(oldProject)) {
						ProjectManager.setActiveProject((getItems().size() > 1) ? getItems().get(1) : null);
						return;
					}

					getSelectionModel().select(oldProject);

					if (fileEditorManager.canOpenAnotherProject())
						ProjectManager.openProject(getScene().getWindow());
				} else {
					if (fileEditorManager.canOpenAnotherProject())
						ProjectManager.setActiveProject(newProject);
					else
						getSelectionModel().select(oldProject);
				}
			} finally {
				inSelectionChange = false;
			}
		});
	});

	// listen to projects changes and update combo box
	projects.addListener((ListChangeListener<File>) change -> {
		while (change.next()) {
			if (change.wasAdded()) {
				for (File addedProject : change.getAddedSubList())
					Utils.addSorted(getItems(), addedProject, PROJECT_COMPARATOR);
			}
			if (change.wasRemoved())
				getItems().removeAll(change.getRemoved());
		}
	});

	// listen to active project change and update combo box value
	ProjectManager.activeProjectProperty().addListener((observer, oldProject, newProject) -> {
		setValue(newProject);
	});
}
 
Example 19
Source File: BookInfoController.java    From AudioBookConverter with GNU General Public License v2.0 4 votes vote down vote up
@FXML
    private void initialize() {

        MenuItem menuItem = new MenuItem("Remove");
        genre.setItems(ConverterApplication.getContext().loadGenres());
        menuItem.setOnAction(event -> {
            genre.getItems().remove(genre.getSelectionModel().getSelectedIndex());
            ConverterApplication.getContext().saveGenres();
        });
        ContextMenu contextMenu = new ContextMenu(menuItem);

        genre.setOnContextMenuRequested(event -> {
            if (!genre.getSelectionModel().isEmpty()) {
                contextMenu.show((Node) event.getSource(), Side.RIGHT, 0, 0);
            }
            genre.hide();
        });

        ObservableList<MediaInfo> media = ConverterApplication.getContext().getMedia();
        media.addListener((InvalidationListener) observable -> updateTags(media, media.isEmpty()));

//        ConverterApplication.getContext().addModeChangeListener((observable, oldValue, newValue) -> updateTags(media, ConversionMode.BATCH.equals(newValue)));

//        clearTags();

        SimpleObjectProperty<AudioBookInfo> bookInfo = ConverterApplication.getContext().getBookInfo();

        bookNo.setTextFormatter(new TextFieldValidator(TextFieldValidator.ValidationModus.MAX_INTEGERS, 3).getFormatter());
        year.setTextFormatter(new TextFieldValidator(TextFieldValidator.ValidationModus.MAX_INTEGERS, 4).getFormatter());

        title.textProperty().addListener(o -> bookInfo.get().title().set(title.getText()));

        writer.textProperty().addListener(o -> bookInfo.get().writer().set(writer.getText()));
        narrator.textProperty().addListener(o -> bookInfo.get().narrator().set(narrator.getText()));

        genre.valueProperty().addListener(o -> bookInfo.get().genre().set(genre.getValue()));
        genre.getEditor().textProperty().addListener(o -> bookInfo.get().genre().set(genre.getEditor().getText()));

        series.textProperty().addListener(o -> bookInfo.get().series().set(series.getText()));
        bookNo.textProperty().addListener(o -> {
            if (StringUtils.isNotBlank(bookNo.getText()))
                bookInfo.get().bookNumber().set(bookNo.getText());
        });
        year.textProperty().addListener(o -> bookInfo.get().year().set(year.getText()));
        comment.textProperty().addListener(o -> bookInfo.get().comment().set(comment.getText()));

        ConverterApplication.getContext().addBookInfoChangeListener((observable, oldValue, newValue) -> Platform.runLater(() -> copyTags(bookInfo.get())));

    }
 
Example 20
Source File: BallotListService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public final void addListeners() {
    ObservableList<ProposalPayload> payloads = proposalService.getProposalPayloads();
    payloads.addListener(this::onChanged);
}