Java Code Examples for javafx.collections.FXCollections#observableList()

The following examples show how to use javafx.collections.FXCollections#observableList() . 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: SaveRequestDialog.java    From milkman with MIT License 6 votes vote down vote up
public void initialize() {
	requestName.setText(request.getName());
	List<String> collectionNames = getCollectionStrings();
	FilteredList<String> filteredList = new FilteredList<String>(FXCollections.observableList(collectionNames));
	collectionName.textProperty().addListener(obs-> {
        String filter = collectionName.getText(); 
        if(filter == null || filter.length() == 0) {
        	Platform.runLater(() -> filteredList.setPredicate(s -> true));
        }
        else {
        	Platform.runLater(() -> filteredList.setPredicate(s -> StringUtils.containsLettersInOrder(s, filter)));
        }
	});
	collectionList.setItems(filteredList);
	
	
	collectionList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
	collectionList.getSelectionModel().selectedItemProperty().addListener((obs, o, n) -> { 
		if (n != null && n.length() > 0)
			collectionName.setText(n);
	});
}
 
Example 2
Source File: ParameterSheetView.java    From old-mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
public ParameterSheetView(ParameterSet parameters, ValidationSupport validationSupport) {

  super((ObservableList) FXCollections.observableList(parameters.getParameters()));

  this.parameters = parameters;

  setModeSwitcherVisible(false);
  setSearchBoxVisible(false);
  setMode(PropertySheet.Mode.NAME);
  setPrefSize(600.0, 400.0);

  // Set editor factory to keep track of which editing component belongs
  // to which parameter
  this.editorFactory = new ParameterEditorFactory(validationSupport);
  setPropertyEditorFactory(editorFactory);

}
 
Example 3
Source File: PieChartDemo.java    From Java-11-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
private PieChart getStudentCountByOccupation(
	List<Student> students,
	Function<Student, String> classifier
){
	Map<String, Long> occupationBreakUp = 
       	students.stream().collect(
   			Collectors.groupingBy(
   				classifier,
   				Collectors.counting()
   			)
   		);
       List<PieChart.Data> pieChartData = 
       	new ArrayList<>();

       occupationBreakUp.forEach((k, v) -> {
       	pieChartData.add(new PieChart.Data(k.toString(), v));
       });

       PieChart chart = new PieChart(
       	FXCollections.observableList(pieChartData)
       );
       return chart;
}
 
Example 4
Source File: PieChartDemo.java    From Java-9-Cookbook with MIT License 6 votes vote down vote up
private PieChart getStudentCountByOccupation(
	List<Student> students,
	Function<Student, String> classifier
){
	Map<String, Long> occupationBreakUp = 
       	students.stream().collect(
   			Collectors.groupingBy(
   				classifier,
   				Collectors.counting()
   			)
   		);
       List<PieChart.Data> pieChartData = 
       	new ArrayList<>();

       occupationBreakUp.forEach((k, v) -> {
       	pieChartData.add(new PieChart.Data(k.toString(), v));
       });

       PieChart chart = new PieChart(
       	FXCollections.observableList(pieChartData)
       );
       return chart;
}
 
Example 5
Source File: Histogram.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
public Histogram(int n) {
	super(new CategoryAxis(), new NumberAxis());
	this.n = n;
	this.getData().add(series);
	List<Data<String,Number>> values = new ArrayList<>();
	for (int i = 0; i < n; i++) {
		values.add(new Data<>("" + i, 0));
	}
	histogramData = FXCollections.observableList(values);
	series.setData(histogramData);
	((NumberAxis)getYAxis()).setMinorTickVisible(false); // only show integers
	
	/* reasonable layout */
	this.setAnimated(false);
	this.setLegendVisible(false);
	((NumberAxis) getYAxis()).setTickUnit(1);
	((NumberAxis) getYAxis()).setTickLabelFormatter(new IntegerAxisFormatter());
	((NumberAxis) getYAxis()).setMinorTickCount(0);
}
 
Example 6
Source File: ThemeManager.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param currentTheme The current theme
 */
public ThemeManager(ObjectProperty<Theme> currentTheme) {
    super();

    this.currentTheme = currentTheme;

    this.defaultCategoryIconsStylesheets = FXCollections.observableArrayList();
    this.defaultLibraryCategoryIconsStylesheets = FXCollections.observableArrayList();
    this.defaultEngineIconsStylesheets = FXCollections.observableArrayList();

    // the base stylesheets
    final ObservableList<String> baseStylesheets = FXCollections
            .observableList(getStylesheets(Themes.STANDARD));
    // the currently selected stylesheets (empty if the the selected theme is the standard theme)
    final ObservableList<String> currentStylesheets = CollectionBindings
            .mapToList(currentTheme, this::getNonStandardStylesheets);

    this.stylesheets = ConcatenatedList.create(
            defaultCategoryIconsStylesheets,
            defaultLibraryCategoryIconsStylesheets,
            defaultEngineIconsStylesheets,
            baseStylesheets,
            currentStylesheets);

    final ObjectBinding<Optional<URI>> currentWebEngineUri = ObjectBindings.map(currentTheme,
            theme -> theme.getResourceUri("description.css"));
    final StringBinding currentWebEngineStylesheet = StringBindings.map(currentWebEngineUri,
            uri -> uri.map(URI::toString).orElse(null));

    this.webEngineStylesheet = Bindings
            .when(Bindings.isNull(currentWebEngineStylesheet))
            .then(Themes.STANDARD.getResourceUri("description.css").map(URI::toString)
                    .orElseThrow(
                            () -> new IllegalStateException("Standard theme contains no \"description.css\" file")))
            .otherwise(currentWebEngineStylesheet);
}
 
Example 7
Source File: CFieldSearcher.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void forceUpdateData(DataElt dataelt) {

	if (!(dataelt instanceof ArrayDataElt))
		throw new RuntimeException(
				String.format("inline page data does not have expected %s type, actually found %s",
						dataelt.getName(), dataelt.getType()));
	data = (ArrayDataElt<ObjectDataElt>) dataelt;
	ArrayList<String> itemstoshow = new ArrayList<String>();
	for (int i = 0; i < data.getObjectNumber(); i++) {
		ObjectDataElt thisobject = data.getObjectAtIndex(i);
		SimpleDataElt fieldtoshowobject = thisobject.lookupEltByName(fieldtoshow);
		if (fieldtoshowobject == null)
			throw new RuntimeException("field not found in object " + fieldtoshow + ", all object fields = "
					+ thisobject.dropFieldNames());
		itemstoshow.add(fieldtoshowobject.defaultTextRepresentation());
	}
	ObservableList<String> itemstoshowlist = FXCollections.observableList(itemstoshow);
	resultlist.setItems(itemstoshowlist);
	double wx = searchfield.getScene().getX() + searchfield.getScene().getWindow().getX();
	double wy = searchfield.getScene().getY() + searchfield.getHeight() + searchfield.getScene().getWindow().getY();
	Point2D point = searchfield.localToScene(0, 0);
	if (this.hasbottomaction) {
		boolean showbottomaction = false;
		if (this.showonlyifempty)
			if (itemstoshow.size() == 0)
				showbottomaction = true;
		if (!this.showonlyifempty)
			showbottomaction = true;
		if (showbottomaction)
			resultbox.getChildren().add(bottombutton);
	}

	resultpopup.show(searchfield, wx + point.getX(), wy + point.getY());

}
 
Example 8
Source File: ComboParameter.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public ComboParameter(@Nonnull String name, @Nonnull String description, @Nonnull String category,
    @Nullable ParameterValidator<ValueType> validator, @Nonnull List<ValueType> options,
    @Nullable ValueType defaultValue) {
  super(name, description, category, (Class) ComboEditor.class, validator);
  this.options = FXCollections.observableList(options);
  setValue(defaultValue);
}
 
Example 9
Source File: ManageEnvironmentsDialog.java    From milkman with MIT License 5 votes vote down vote up
public void showAndWait(List<Environment> envs) {
	this.originalList = envs;
	JFXDialogLayout content = new ManageEnvironmentsDialogFxml(this);
	JavaFxUtils.publishEscToParent(environmentList);

	environments = FXCollections.observableList(envs);
	environmentList.setItems(environments);
	environmentList.setCellFactory(l -> new EnvironmentCell());
	environmentList.setSelectionModel(new NoSelectionModel<Environment>());
	environmentList.setPlaceholder(new Label("No Environments created..."));
	dialog = FxmlUtil.createDialog(content);
	dialog.showAndWait();
}
 
Example 10
Source File: ConfigurationUIController.java    From jace with GNU General Public License v2.0 5 votes vote down vote up
private Node buildDynamicSelectComponent(ConfigNode node, String settingName, Serializable value) {
    try {
        DynamicSelection sel = (DynamicSelection) node.subject.getClass().getField(settingName).get(node.subject);
        ChoiceBox widget = new ChoiceBox(FXCollections.observableList(new ArrayList(sel.getSelections().keySet())));
        widget.setMinWidth(175.0);
        widget.setConverter(new StringConverter() {
            @Override
            public String toString(Object object) {
                return (String) sel.getSelections().get(object);
            }
            
            @Override
            public Object fromString(String string) {
                return sel.findValueByMatch(string);
            }
        });
        Object selected = value == null ? null : widget.getConverter().fromString(String.valueOf(value));
        if (selected == null) {
            widget.getSelectionModel().selectFirst();
        } else {
            widget.setValue(selected);
        }
        widget.valueProperty().addListener((Observable e) -> {
            node.setFieldValue(settingName, widget.getConverter().toString(widget.getValue()));
        });
        return widget;
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
        Logger.getLogger(ConfigurationUIController.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
 
Example 11
Source File: CreatorEditingTableCell.java    From tcMenu with Apache License 2.0 5 votes vote down vote up
private void buildComboBox(CreatorProperty prop) {
    var comboBox = new ComboBox<String>(FXCollections.observableList(prop.getValidationRules().choices()));
    comboBox.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
    comboBox.focusedProperty().addListener((ObservableValue<? extends Boolean> o, Boolean old, Boolean newVal) -> {
                if (!newVal) {
                    commitEdit(comboBox.getValue());
                }
    });
    comboBox.setOnAction(actionEvent -> commitEdit(comboBox.getValue()));
    editorNode = comboBox;
}
 
Example 12
Source File: MainMenuPaneTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void testInitialize() {
  final NavigationPane mock = mock(NavigationPane.class);
  final StackPane mock2 = mock(StackPane.class);
  final Label mock3 = mock(Label.class);
  final Node mock4 = mock(Node.class);
  final NavigationPane mock5 = mock(NavigationPane.class);
  final ObservableList<Node> children = FXCollections.observableList(new ArrayList<>());

  when(mock.getNode()).thenReturn(mock4);
  when(mock2.getChildren()).thenReturn(children);
  when(mock3.getText()).thenReturn("Test String {0}");

  final MainMenuPane aboutInformation = new MainMenuPane(() -> mock, null, mock2, mock3);

  aboutInformation.initialize();

  verify(mock3).setText("Test String " + ClientContext.engineVersion().toString());
  assertEquals(1, children.size());
  assertEquals(mock4, children.get(0));

  verify(mock).registerScreen(FxmlManager.GAME_SELECTION_CONTROLS);
  verify(mock).registerScreen(FxmlManager.MAIN_MENU_CONTROLS);

  verify(mock).switchScreen(FxmlManager.MAIN_MENU_CONTROLS);

  aboutInformation.connect(mock5);

  verify(mock).setParent(mock5);
}
 
Example 13
Source File: CurrencyList.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public ObservableList<CurrencyListItem> getObservableList() {
    return FXCollections.observableList(delegate);
}
 
Example 14
Source File: VertexGraphLabelsEditorFactory.java    From constellation with Apache License 2.0 4 votes vote down vote up
LabelEntry(final List<LabelEntry> host, final Pane visualHost, final String attributeName, final ConstellationColor color, final float size) {

                attrCombo = new ComboBox<>(FXCollections.observableList(attributeNames));
                attrCombo.setPrefWidth(150);
                attrCombo.getSelectionModel().select(attributeName);
                attrCombo.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
                    update();
                });

                colorRect = new Rectangle(20, 20);
                this.color = color.getJavaFXColor();
                colorRect.setFill(this.color);
                colorRect.setStroke(Color.LIGHTGREY);
                colorRect.setOnMouseClicked(getChooseColorEventHandler());

                sizeText = new TextField(String.valueOf(size));
                sizeText.setPrefWidth(50);
                sizeText.textProperty().addListener((o, n, v) -> {
                    update();
                });

                final Button upButton = new Button("", new ImageView(UserInterfaceIconProvider.CHEVRON_UP.buildImage(16)));
                upButton.setOnAction(e -> {
                    moveUp();
                    update();
                });
                final Button downButton = new Button("", new ImageView(UserInterfaceIconProvider.CHEVRON_DOWN.buildImage(16)));
                downButton.setOnAction(e -> {
                    moveDown();
                    update();
                });
                final Button removeButton = new Button("", new ImageView(UserInterfaceIconProvider.CROSS.buildImage(16)));
                removeButton.setOnAction(e -> {
                    remove();
                    update();
                });

                entry = new HBox(10);
                entry.getChildren().addAll(attrCombo, colorRect, sizeText, upButton, downButton, removeButton);

                this.host = host;
                this.host.add(this);
                this.visualHost = visualHost;
                this.visualHost.getChildren().add(entry);
            }
 
Example 15
Source File: DisplayPhotosController.java    From Augendiagnose with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Display the pictures for a given name.
 *
 * @param name
 *            The name.
 */
private void showPicturesForName(final String name) {
	File nameFolder = new File(PreferenceUtil.getPreferenceString(KEY_FOLDER_PHOTOS), name);

	ProgressDialog dialog =
			DialogUtil.displayProgressDialog(ResourceConstants.MESSAGE_PROGRESS_LOADING_PHOTOS, name);

	EyePhotoPair[] eyePhotos = createEyePhotoList(nameFolder);

	ObservableList<GridPane> valuesPhotos = FXCollections.observableList(new ArrayList<GridPane>());

	for (int i = 0; i < eyePhotos.length; i++) {
		EyePhotoPairNode eyePhotoPairNode = new EyePhotoPairNode(eyePhotos[i], this);
		valuesPhotos.add(eyePhotoPairNode);

		// Workaround to ensure that the scrollbar is correctly resized after the images are loaded.
		eyePhotoPairNode.getImagesLoadedProperty().addListener(new ChangeListener<Boolean>() {
			@Override
			public void changed(final ObservableValue<? extends Boolean> observable,
					final Boolean oldValue,
					final Boolean newValue) {
				Platform.runLater(new Runnable() {
					@Override
					public void run() {
						GridPane dummy = new GridPane();
						valuesPhotos.add(dummy);
						mListPhotos.layout();
						valuesPhotos.remove(dummy);
					}
				});
			}
		});
	}

	mPreviousName = name;

	Platform.runLater(new Runnable() {
		@Override
		public void run() {
			mListPhotos.setItems(valuesPhotos);
			dialog.close();
		}
	});
}
 
Example 16
Source File: GUI.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
private TableView<Instance> createTable()
{
    final TableView<Instance> table = new TableView<>(FXCollections.observableList(model.getInstances()));
    table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    table.getSelectionModel().setCellSelectionEnabled(true);

    table.setEditable(true);

    TableColumn<Instance, String> col = new TableColumn<>(Messages.SystemColumn);
    col.setCellValueFactory(cell -> new SimpleStringProperty(cell.getValue().getName()));
    table.getColumns().add(col);

    int col_index = 0;
    for (Column column : model.getColumns())
    {
        final int the_col_index = col_index;
        col = new TableColumn<>(column.getName());
        col.setCellFactory(info -> new PACETableCell());
        col.setCellValueFactory(cell -> cell.getValue().getCell(the_col_index).getObservable());
        table.getColumns().add(col);

        if (column.isReadonly())
            col.setEditable(false);
        else
        {
            col.setOnEditCommit(event ->
            {
                event.getRowValue().getCell(the_col_index).setUserValue(event.getNewValue());
                final int row = event.getTablePosition().getRow();
                // Start to edit same column in next row
                if (row < table.getItems().size() - 1)
                    Platform.runLater(() ->  table.edit(row+1, event.getTableColumn()));
            });
        }

        ++col_index;
    }

    return table;
}
 
Example 17
Source File: JfxTableEditor.java    From milkman with MIT License 4 votes vote down vote up
public void setItems(List<T> items, Comparator<T> comparator) {
		List<RecursiveWrapper<T>> wrappedItems = items.stream().map(i -> new RecursiveWrapper<>(i)).collect(Collectors.toList());
		obsWrappedItems = FXCollections.observableList(wrappedItems);
		if (comparator != null) {
			FXCollections.sort(obsWrappedItems, (ra, rb) -> comparator.compare(ra.getData(), rb.getData()));
		}
		
		
		obsWrappedItems.addListener(new ListChangeListener<RecursiveWrapper<T>>() {

			@Override
			public void onChanged(Change<? extends RecursiveWrapper<T>> c) {
				//forward removals:
				if (!c.next())
					return;
				
				if (c.wasRemoved()) {
					for(var ri : c.getRemoved()) {
						items.remove(ri.getData());
					}
				}
				
				if (c.wasAdded()) {
					RecursiveWrapper<T> newEntry = c.getAddedSubList().get(0);
					items.add(newEntry.getData());
				}
			}
		});
		
		final TreeItem<RecursiveWrapper<T>> root = new RecursiveTreeItem<>(obsWrappedItems, RecursiveTreeObject::getChildren); 
		table.setRoot(root);
		
		Platform.runLater(() -> {
			table.resizeColumns();
		});
		
		//register double-click listener for empty rows, to add a new instance
//		this.setRowFactory(view -> {
//		    TableRow<T> row = new TableRow<T>();
//		    row.setOnMouseClicked(event -> {
//			    if (row.isEmpty() && (event.getClickCount() == 2)) {
//			        T myItem = newItemCreator.get();
//			        getItems().add(myItem);
//			    } 
//			});
//		    return row;
//		});
		
		//we cant click on row if there is no row, so we have to register another event handler
		//for when the table is empty
//		this.setOnMouseClicked(event -> {
//		    if (getItems().isEmpty() && (event.getClickCount() == 2)) {
//		        T myItem = newItemCreator.get();
//		        getItems().add(myItem);
//		    } 
//		});
		
	}
 
Example 18
Source File: PackageItem.java    From TerasologyLauncher with Apache License 2.0 4 votes vote down vote up
PackageItem(final String name, final List<VersionItem> versions) {
    this.name = new SimpleStringProperty(name);
    versionItems = FXCollections.observableList(versions);
}
 
Example 19
Source File: DecoratorsEditorFactory.java    From constellation with Apache License 2.0 4 votes vote down vote up
@Override
protected Node createEditorControls() {
    // get all vertex attributes currently in the graph
    final List<String> attributeNames = new ArrayList<>();
    ReadableGraph rg = GraphManager.getDefault().getActiveGraph().getReadableGraph();
    try {
        for (int i = 0; i < rg.getAttributeCount(GraphElementType.VERTEX); i++) {
            attributeNames.add(rg.getAttributeName(rg.getAttribute(GraphElementType.VERTEX, i)));
        }
    } finally {
        rg.release();
    }
    Collections.sort(attributeNames);
    attributeNames.add(0, NO_DECORATOR);

    final Label nwLabel = new Label("NW:");
    final Label neLabel = new Label("NE:");
    final Label seLabel = new Label("SE:");
    final Label swLabel = new Label("SW:");
    nwCombo = new ComboBox<>(FXCollections.observableList(attributeNames));
    nwCombo.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
        update();
    });
    neCombo = new ComboBox<>(FXCollections.observableList(attributeNames));
    neCombo.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
        update();
    });
    seCombo = new ComboBox<>(FXCollections.observableList(attributeNames));
    seCombo.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
        update();
    });
    swCombo = new ComboBox<>(FXCollections.observableList(attributeNames));
    swCombo.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
        update();
    });

    final GridPane controls = new GridPane();
    controls.getColumnConstraints().add(new ColumnConstraints(50));
    controls.setVgap(CONTROLS_DEFAULT_VERTICAL_SPACING);
    controls.addRow(0, nwLabel, nwCombo);
    controls.addRow(3, neLabel, neCombo);
    controls.addRow(2, seLabel, seCombo);
    controls.addRow(1, swLabel, swCombo);

    return controls;
}
 
Example 20
Source File: TransactionGraphLabelsEditorFactory.java    From constellation with Apache License 2.0 4 votes vote down vote up
LabelEntry(final List<LabelEntry> host, final Pane visualHost, final String attributeName, final ConstellationColor color, final float size) {
    attrCombo = new ComboBox<>(FXCollections.observableList(attributeNames));
    attrCombo.setPrefWidth(150);
    attrCombo.getSelectionModel().select(attributeName);
    attrCombo.getSelectionModel().selectedItemProperty().addListener((o, n, v) -> {
        update();
    });

    colorRect = new Rectangle(20, 20);
    this.color = color.getJavaFXColor();
    colorRect.setFill(this.color);
    colorRect.setStroke(Color.LIGHTGREY);
    colorRect.setOnMouseClicked(getChooseColorEventHandler());

    sizeText = new TextField(String.valueOf(size));
    sizeText.setPrefWidth(50);
    sizeText.textProperty().addListener((o, n, v) -> {
        update();
    });

    final Button upButton = new Button("", new ImageView(UserInterfaceIconProvider.CHEVRON_UP.buildImage(16)));
    upButton.setOnAction(e -> {
        moveUp();
        update();
    });
    final Button downButton = new Button("", new ImageView(UserInterfaceIconProvider.CHEVRON_DOWN.buildImage(16)));
    downButton.setOnAction(e -> {
        moveDown();
        update();
    });
    final Button removeButton = new Button("", new ImageView(UserInterfaceIconProvider.CROSS.buildImage(16)));
    removeButton.setOnAction(e -> {
        remove();
        update();
    });

    entry = new HBox(10);
    entry.getChildren().addAll(attrCombo, colorRect, sizeText, upButton, downButton, removeButton);

    this.host = host;
    this.host.add(this);
    this.visualHost = visualHost;
    this.visualHost.getChildren().add(entry);
}