Java Examples for javafx.collections.FXCollections

The following java examples will help you to understand the usage of javafx.collections.FXCollections. These source code samples are taken from different open source projects.

Example 1
Project: lighthouse-master  File: ObservableMirrorsTest.java View source code
@Test
public void mirroredSet() throws Exception {
    ObservableSet<String> source = FXCollections.observableSet();
    source.add("alpha");
    source.add("beta");
    ObservableSet<String> dest = ObservableMirrors.mirrorSet(source, gate);
    assertEquals(0, gate.getTaskQueueSize());
    assertEquals(2, dest.size());
    source.add("delta");
    assertEquals(1, gate.getTaskQueueSize());
    assertEquals(2, dest.size());
    gate.waitAndRun();
    assertEquals(0, gate.getTaskQueueSize());
    assertEquals(3, dest.size());
    source.removeAll(ImmutableList.of("alpha", "beta"));
    assertEquals(2, gate.getTaskQueueSize());
    gate.waitAndRun();
    gate.waitAndRun();
    assertEquals(1, dest.size());
    assertTrue(dest.contains("delta"));
}
Example 2
Project: downlords-faf-client-master  File: Ranked1v1ControllerTest.java View source code
@Before
public void setUp() throws Exception {
    instance = loadController("ranked_1v1.fxml");
    instance.gameService = gameService;
    instance.preferencesService = preferencesService;
    instance.playerService = playerService;
    instance.environment = environment;
    instance.leaderboardService = leaderboardService;
    instance.i18n = i18n;
    PlayerInfoBean playerInfoBean = new PlayerInfoBean(USERNAME);
    playerInfoBean.setId(PLAYER_ID);
    currentPlayerProperty = new SimpleObjectProperty<>(playerInfoBean);
    factionList = FXCollections.observableArrayList();
    Ranked1v1EntryBean ranked1v1EntryBean = new Ranked1v1EntryBean();
    ranked1v1EntryBean.setRating(500);
    ranked1v1EntryBean.setWinLossRatio(12.23f);
    ranked1v1EntryBean.setRank(100);
    ranked1v1EntryBean.setGamesPlayed(412);
    ranked1v1EntryBean.setUsername(USERNAME);
    Ranked1v1Stats ranked1v1Stats = new Ranked1v1Stats();
    ranked1v1Stats.setRatingDistribution(new HashMap<>());
    when(leaderboardService.getRanked1v1Stats()).thenReturn(CompletableFuture.completedFuture(ranked1v1Stats));
    when(leaderboardService.getEntryForPlayer(PLAYER_ID)).thenReturn(CompletableFuture.completedFuture(ranked1v1EntryBean));
    when(gameService.searching1v1Property()).thenReturn(searching1v1Property);
    when(preferencesService.getPreferences()).thenReturn(preferences);
    when(preferences.getRanked1v1()).thenReturn(ranked1v1Prefs);
    when(ranked1v1Prefs.getFactions()).thenReturn(factionList);
    when(preferences.getForgedAlliance()).thenReturn(forgedAlliancePrefs);
    when(playerService.getCurrentPlayer()).thenReturn(currentPlayerProperty.get());
    when(playerService.currentPlayerProperty()).thenReturn(currentPlayerProperty);
    when(environment.getProperty("rating.low", int.class)).thenReturn(100);
    when(environment.getProperty("rating.moderate", int.class)).thenReturn(200);
    when(environment.getProperty("rating.good", int.class)).thenReturn(300);
    when(environment.getProperty("rating.high", int.class)).thenReturn(400);
    when(environment.getProperty("rating.top", int.class)).thenReturn(500);
    when(environment.getProperty("rating.beta", int.class)).thenReturn(10);
    instance.postConstruct();
}
Example 3
Project: fhnw-master  File: ApplicationUI.java View source code
@Override
public void setResults(List<Result> results) {
    ObservableList<Result> observableList = FXCollections.observableArrayList();
    observableList.addAll(results);
    tableView.setItems(observableList);
    TableColumn<Result, String> nameColumn = new TableColumn<>("Gemeinde");
    tableView.getColumns().add(nameColumn);
    nameColumn.setCellValueFactory( e -> new ReadOnlyObjectWrapper<>(e.getValue().getCommunityName()));
    TableColumn<Result, String> canton = new TableColumn<>("Kanton");
    tableView.getColumns().add(canton);
    canton.setCellValueFactory( e -> new ReadOnlyObjectWrapper<>(e.getValue().getCanton()));
    TableColumn<Result, Integer> allowed = new TableColumn<>("Wahlberechtigte");
    tableView.getColumns().add(allowed);
    allowed.setCellValueFactory( e -> new ReadOnlyObjectWrapper<>(e.getValue().getEligibleVoters()));
    TableColumn<Result, Integer> voters = new TableColumn<>("Wähler");
    tableView.getColumns().add(voters);
    voters.setCellValueFactory( e -> new ReadOnlyObjectWrapper<>(e.getValue().getEligibleVoters()));
    TableColumn<Result, String> turnout = new TableColumn<>("Wahlbeteiligung");
    tableView.getColumns().add(turnout);
    turnout.setCellValueFactory( e -> new ReadOnlyObjectWrapper<>(String.format("%f%s", 100 * e.getValue().getTurnout(), "%")));
    label.setText(String.format("Wahlergebnisse der %d Gemeinden", results.size()));
}
Example 4
Project: sandboxes-master  File: TableSample.java View source code
@Override
public void start(Stage primaryStage) throws Exception {
    BorderPane borderPane = new BorderPane();
    Group root = new Group();
    primaryStage.setScene(new Scene(root));
    TableView<ANumber> tableView = createTable();
    borderPane.setCenter(tableView);
    root.getChildren().add(borderPane);
    primaryStage.show();
    final ObservableList<ANumber> data = FXCollections.observableArrayList(new ANumber(-9999d), new ANumber(0d), new ANumber(2222d));
    tableView.setItems(data);
}
Example 5
Project: e-fx-clipse-master  File: AlbumContentView.java View source code
@Inject
void setAlbum(@Optional Album album) {
    if (album != null) {
        ObservableList<Media> list = EMFListHelper.adaptList(PhotoeditPackage.Literals.ALBUM__MEDIA, album);
        listView.setItems(list);
    } else {
        ObservableList<Media> list = FXCollections.emptyObservableList();
        listView.setItems(list);
    }
}
Example 6
Project: gef-master  File: ListPropertyExTests.java View source code
@Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] { { new Provider<ListProperty<Integer>>() {

        @Override
        public ListProperty<Integer> get() {
            return new SimpleListPropertyEx<>(FXCollections.observableList(new ArrayList<Integer>()));
        }
    } }, { new Provider<ListProperty<Integer>>() {

        @Override
        public ListProperty<Integer> get() {
            // https://bugs.openjdk.java.net/browse/JDK-8136465)
            return new ReadOnlyListWrapperEx<>(FXCollections.observableList(new ArrayList<Integer>()));
        }
    } } });
}
Example 7
Project: jabref-master  File: GroupNodeViewModelTest.java View source code
@Before
public void setUp() throws Exception {
    stateManager = mock(StateManager.class);
    when(stateManager.getSelectedEntries()).thenReturn(FXCollections.emptyObservableList());
    databaseContext = new BibDatabaseContext();
    taskExecutor = new CurrentThreadTaskExecutor();
    viewModel = getViewModelForGroup(new WordKeywordGroup("Test group", GroupHierarchyType.INDEPENDENT, "test", "search", true, ',', false));
}
Example 8
Project: JFTClient-master  File: LocalTree.java View source code
@Override
public ObservableList<TreeItem<Node>> buildChildren(TreeItem<Node> treeItem) {
    Node f = treeItem.getValue();
    if (f != null && !f.isFile()) {
        File[] files = new File(f.getPath()).listFiles();
        if (files != null) {
            ObservableList<TreeItem<Node>> children = FXCollections.observableArrayList();
            for (File childFile : files) {
                if (!configDao.get().isShowHiddenFiles() && childFile.isHidden()) {
                    continue;
                }
                children.add(createNode(new Node(childFile)));
            }
            Collections.sort(children, ( o1,  o2) -> o1.getValue().compareTo(o2.getValue()));
            return children;
        }
    }
    return FXCollections.emptyObservableList();
}
Example 9
Project: CCAutotyper-master  File: FXConfirmDialog.java View source code
private Parent assemble() {
    final BorderPane root = new BorderPane();
    final HBox btnBox = new HBox(50);
    final Button approve = new Button("Approve");
    final Button reject = new Button("Reject");
    approve.setPrefWidth(BUTTON_WIDTH);
    reject.setPrefWidth(BUTTON_WIDTH);
    ButtonBar buttonBar = new ButtonBar();
    buttonBar.getButtons().addAll(approve, reject);
    ButtonBar.setButtonData(approve, ButtonBar.ButtonData.YES);
    ButtonBar.setButtonData(reject, ButtonBar.ButtonData.NO);
    approve.setDefaultButton(true);
    btnBox.setId("button-box");
    btnBox.setAlignment(Pos.BASELINE_CENTER);
    btnBox.setPadding(new Insets(10, 0, 10, 0));
    btnBox.getChildren().addAll(buttonBar);
    final VBox webBox = new VBox();
    webBox.getChildren().add(this.webView);
    final HBox optBox = new HBox(20);
    final Button cpyBtn = new Button("Copy Code");
    final ComboBox<String> themeColor = new ComboBox<>(FXCollections.observableArrayList(THEMES));
    final ComboBox<String> syntaxes = new ComboBox<>(FXCollections.observableList(ModeParser.getPossibleModes()));
    syntaxes.getSelectionModel().select(this.mode.displayName);
    themeColor.getSelectionModel().select(this.theme);
    cpyBtn.setPrefWidth(BUTTON_WIDTH);
    syntaxes.getSelectionModel().selectedItemProperty().addListener(( obs,  oldValue,  newValue) -> {
        if (newValue == null)
            return;
        FXConfirmDialog.this.mode = ModeParser.getModeFor(newValue);
        FXConfirmDialog.this.webView.getEngine().loadContent(getFormattedTemplate());
    });
    themeColor.getSelectionModel().selectedItemProperty().addListener(( obs,  oldValue,  newValue) -> {
        if (newValue == null)
            return;
        FXConfirmDialog.this.theme = newValue.toLowerCase();
        FXConfirmDialog.this.webView.getEngine().loadContent(getFormattedTemplate());
    });
    optBox.setId("menu-bar");
    optBox.setAlignment(Pos.CENTER_LEFT);
    optBox.setPadding(new Insets(10, 0, 10, 10));
    optBox.getChildren().addAll(cpyBtn, syntaxes, themeColor);
    root.setTop(optBox);
    root.setCenter(webBox);
    root.setBottom(btnBox);
    VBox.setVgrow(this.webView, Priority.ALWAYS);
    syntaxes.setEditable(false);
    approve.setOnAction(( e) -> {
        FXConfirmDialog.this.approved = true;
        hide();
    });
    reject.setOnAction(( e) -> {
        FXConfirmDialog.this.approved = false;
        hide();
    });
    cpyBtn.setOnAction(( e) -> {
        final String code = getCodeAndSnapshot();
        final Clipboard clip = Clipboard.getSystemClipboard();
        final ClipboardContent content = new ClipboardContent();
        content.putString(code);
        Platform.runLater(() -> clip.setContent(content));
    });
    return root;
}
Example 10
Project: closurefx-builder-master  File: JSLanguageSectionController.java View source code
/**
     * Initializes the controller class.
     */
@Override
public void initialize(URL url, ResourceBundle rb) {
    controlInputLanguage.setItems(FXCollections.observableArrayList(LangType.values()));
    controlInputLanguage.setButtonCell(new JSLanguageSectionController.LanguageCellFactory());
    controlInputLanguage.setCellFactory(new Callback<ListView<LangType>, ListCell<LangType>>() {

        @Override
        public ListCell<LangType> call(ListView<LangType> p) {
            return new JSLanguageSectionController.LanguageCellFactory();
        }
    });
    controlOutputLanguage.setItems(FXCollections.observableArrayList(LangType.values()));
    controlOutputLanguage.setButtonCell(new JSLanguageSectionController.LanguageCellFactory());
    controlOutputLanguage.setCellFactory(new Callback<ListView<LangType>, ListCell<LangType>>() {

        @Override
        public ListCell<LangType> call(ListView<LangType> p) {
            return new JSLanguageSectionController.LanguageCellFactory();
        }
    });
}
Example 11
Project: context-master  File: SyntaxBasedConfigurationController.java View source code
/**
     *
     * @param url
     * @param rb
     */
@Override
public void initialize(URL url, ResourceBundle rb) {
    labelMaps = new HashMap<String, List<String>>();
    labelMaps.put("V", Arrays.asList("VB", "VBD", "VBG", "VBN", "VBP", "VBZ"));
    labelMaps.put("CN", Arrays.asList("NN", "NNS"));
    labelMaps.put("PN", Arrays.asList("NNP", "NNPS"));
    labelMaps.put("PNN", Arrays.asList("PRP", "PRP$", "WP", "WP$"));
    labelMaps.put("ADJ", Arrays.asList("JJ", "JJR", "JJS"));
    labelMaps.put("M", Arrays.asList("MD"));
    labelMaps.put("NUM", Arrays.asList("CD"));
    labelMaps.put("CC", Arrays.asList("CC", "IN"));
    labelMaps.put("FW", Arrays.asList("FW"));
    labelMaps.put("SYM", Arrays.asList("SYM"));
    labelMaps.put("INJ", Arrays.asList("UH"));
    final CheckBox[][] checkboxes = new CheckBox[names.size()][names.size()];
    this.checkboxes = checkboxes;
    gridContainerVBox.getChildren().add(CustomGridPane.addGridPane(names, abbr, checkboxes));
    //        ObservableList<String> codebookMethodOptions
    //                = FXCollections.observableArrayList(
    //                        "Normalization",
    //                        "Entity Class Encoding"
    //                );
    //        codebookMethodComboBox.getItems().addAll(codebookMethodOptions);
    //        codebookMethodComboBox.getSelectionModel().select(0);
    //        ObservableList<String> codebookModeOptions
    //                = FXCollections.observableArrayList(
    //                        "Replace and Insert", //0
    //                        "Positive Filter", //1
    //                        "Positive Filter with Placeholder" //2
    //                );
    //        codebookModeComboBox.getItems().addAll(codebookModeOptions);
    //        codebookModeComboBox.getSelectionModel().select(2);
    //        ObservableList<String> networkTypeOptions
    //                = FXCollections.observableArrayList(
    //                        "One-mode Network",
    //                        "Multi-mode Network"
    //                );
    //        networkTypeComboBox.getItems().addAll(networkTypeOptions);
    //        networkTypeComboBox.getSelectionModel().select(0);
    ObservableList<String> aggregationOptions = FXCollections.observableArrayList("Per Document", "Per Corpus");
    aggregationComboBox.getItems().addAll(aggregationOptions);
    aggregationComboBox.getSelectionModel().select(1);
//        ObservableList<String> unitOfAnalysisOptions
//                = FXCollections.observableArrayList(
//                        "Sentence",
//                        "Paragraph",
//                        "Text",
//                        "Custom Tag..."
//                );
//        unitOfAnalysisComboBox.getItems().addAll(unitOfAnalysisOptions);
//        unitOfAnalysisComboBox.getSelectionModel().select(0);
//        distanceTextField.setText(AppConfig.getProperty("task.lexisnexisparse.distance"));
//        customTagTextField.setVisible(false);
}
Example 12
Project: cssfx-master  File: ApplicationStages.java View source code
public static ObservableList<Stage> monitoredStages(Stage... restrictedTo) {
    try {
        Class<?> sh = Class.forName("com.sun.javafx.stage.StageHelper");
        Method m = sh.getMethod("getStages");
        ObservableList<Stage> stages = (ObservableList<Stage>) m.invoke(null, new Object[0]);
        logger(ApplicationStages.class).debug("successfully retrieved JavaFX stages from com.sun.javafx.stage.StageHelper");
        return stages;
    } catch (Exception e) {
        logger(ApplicationStages.class).error("cannot observe stages changes by calling com.sun.javafx.stage.StageHelper.getStages()", e);
    }
    return FXCollections.emptyObservableList();
}
Example 13
Project: fancy-chart-master  File: DataItemDao.java View source code
public static List<DataItem> importFromFile(String filePath, FileFormat fileFormat) {
    if (filePath != null) {
        switch(fileFormat) {
            case CSV:
                SortedMap<Number, Number> csvData = CsvDao.importCsv(filePath);
                return createDataItems(csvData);
            case XLS:
                SortedMap<Number, Number> xlsData = XlsDao.importXls(filePath);
                return createDataItems(xlsData);
            case HDF5:
                SortedMap<Number, Number> hdf5Data = Hdf5Dao.importHdf5(filePath);
                return createDataItems(hdf5Data);
            default:
                break;
        }
    }
    return FXCollections.observableArrayList();
}
Example 14
Project: itol-master  File: DlgConfigure.java View source code
private void updateData(boolean save) {
    if (save) {
        config.setLogFile(edLogFile.getText());
        config.setLogLevel(cbLogLevel.getSelectionModel().getSelectedItem().getId());
        config.setMsgFileFormat(autoCompletionAttachMailAs.getSelectedItem());
        config.setInjectIssueIdIntoMailSubject(ckInsertIssueId.isSelected());
        config.setExportAttachmentsDirectory(edExportAttachmentsDirectory.getText());
        config.setAutoReplyField(edAutoReplyField.getText());
        String mailBodyConversionId = cbMailBody.getSelectionModel().getSelectedItem().getId();
        config.setMailBodyConversion(MailBodyConversion.valueOf(mailBodyConversionId));
        ObservableList<AttachmentBlacklistItem> blacklistItems = tvBlacklist.getItems();
        config.setBlacklist(blacklistItems);
        config.setExportAttachmentsProgram(cbExportAttachmentsProgram.getEditor().getText());
    } else {
        edLogFile.setText(config.getLogFile());
        cbLogLevel.getSelectionModel().select(new IdName(config.getLogLevel(), ""));
        String fileTypeId = config.getMsgFileFormat().getId();
        for (IdName item : MsgFileFormat.FORMATS) {
            if (item.getId().equals(fileTypeId)) {
                autoCompletionAttachMailAs.select(item);
                break;
            }
        }
        IdName mailBodyConversionItem = new IdName(config.getMailBodyConversion().toString(), "");
        cbMailBody.getSelectionModel().select(mailBodyConversionItem);
        ckInsertIssueId.setSelected(config.getInjectIssueIdIntoMailSubject());
        edExportAttachmentsDirectory.setText(config.getExportAttachmentsDirectory());
        edAutoReplyField.setText(config.getAutoReplyField());
        ObservableList<AttachmentBlacklistItem> blacklistItems = FXCollections.observableArrayList(config.getBlacklist());
        tvBlacklist.setItems(blacklistItems);
        cbExportAttachmentsProgram.getEditor().setText(config.getExportAttachmentsProgram());
    }
}
Example 15
Project: joa-master  File: MyTaskPane.java View source code
@Override
public Scene createScene() throws ComException {
    // Creating a GridPane container
    GridPane grid = new GridPane();
    grid.setPadding(new Insets(10, 10, 10, 10));
    grid.setVgap(5);
    grid.setHgap(5);
    // Defining the Name text field
    TextField name = new TextField();
    name.setPromptText("Enter your 111 name.");
    name.setPrefColumnCount(10);
    name.getText();
    GridPane.setConstraints(name, 0, 0);
    grid.getChildren().add(name);
    // Defining the Last Name text field
    final TextField lastName = new TextField();
    lastName.setPromptText("Enter your last name.");
    GridPane.setConstraints(lastName, 0, 1);
    grid.getChildren().add(lastName);
    // Defining the Comment text field
    final TextField comment = new TextField();
    comment.setPrefColumnCount(15);
    comment.setPromptText("Enter your comment.");
    GridPane.setConstraints(comment, 0, 2);
    grid.getChildren().add(comment);
    // Defining the Submit button
    Button submit = new Button("Submit");
    GridPane.setConstraints(submit, 1, 0);
    grid.getChildren().add(submit);
    // Defining the Clear button
    Button clear = new Button("Hide Task Pane");
    GridPane.setConstraints(clear, 1, 1);
    grid.getChildren().add(clear);
    ComboBox<String> cbCats = new ComboBox<String>(FXCollections.observableArrayList("alpha", "beta", "gamma"));
    GridPane.setConstraints(cbCats, 0, 3);
    grid.getChildren().add(cbCats);
    final Scene scene = new Scene(grid);
    submit.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent event) {
            // Stage dialog = new Stage();
            // dialog.initStyle(StageStyle.UTILITY);
            // Scene scene = new Scene(new Group(new Text(25, 25,
            // "Hello World!")));
            // dialog.setScene(scene);
            // dialog.show();
            BackgTask.run(() -> {
                try {
                    Dispatch mailItem = (Dispatch) MyOutlookAddin.getInstance().getApplication().CreateItem(OlItemType.olMailItem);
                    mailItem._call("Display");
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            });
        }
    });
    clear.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent event) {
            try {
                customTaskPane.setVisible(false);
            } catch (ComException e) {
                e.printStackTrace();
            }
        }
    });
    return scene;
}
Example 16
Project: jointry-master  File: MultiKeyButton.java View source code
public ObservableList<KeyButton> getExtKeyCodes() {
    if (extKeyCodes == null) {
        extKeyCodes = FXCollections.observableArrayList();
        extKeyCodes.addListener(new ListChangeListener<KeyButton>() {

            public void onChanged(Change<? extends KeyButton> c) {
                while (c.next()) {
                    for (KeyButton button : c.getAddedSubList()) {
                        getContext().getButtons().add(button);
                    }
                }
            }
        });
    }
    return extKeyCodes;
}
Example 17
Project: metastone-master  File: EditorMainWindow.java View source code
private void setupAttributeBoxes() {
    for (ComboBox<Attribute> comboBox : attributeBoxes) {
        ObservableList<Attribute> items = FXCollections.observableArrayList();
        items.addAll(Attribute.values());
        Collections.sort(items, ( obj1,  obj2) -> {
            if (obj1 == obj2) {
                return 0;
            }
            if (obj1 == null) {
                return -1;
            }
            if (obj2 == null) {
                return 1;
            }
            return obj1.toString().compareTo(obj2.toString());
        });
        comboBox.setItems(items);
        comboBox.valueProperty().addListener(( ov,  oldValue,  newValue) -> onAttributesChanged());
        comboBox.setOnKeyReleased(new ComboBoxKeyHandler<Attribute>(comboBox));
    }
    for (TextField attributeField : attributeFields) {
        attributeField.textProperty().addListener(( ov,  oldValue,  newValue) -> onAttributesChanged());
    }
}
Example 18
Project: MiscellaneousStudy-master  File: TableViewSample.java View source code
@Override
public void start(Stage stage) {
    // TableView �ルート�素を指定���らインスタンス化
    TableView<TableData> tableView = new TableView<>();
    // 列�定義
    TableColumn<TableData, String> firstNameCol = new TableColumn<>("First Name");
    firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
    TableColumn<TableData, String> lastNameCol = new TableColumn<>("Last Name");
    lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
    ObservableList<TableColumn<TableData, ?>> columns = tableView.getColumns();
    columns.add(firstNameCol);
    columns.add(lastNameCol);
    // テーブルレコード�作�
    ObservableList<TableData> tableDatas = FXCollections.observableArrayList();
    TableData tableData01 = new TableData("First", "Last");
    tableDatas.add(tableData01);
    TableData tableData02 = new TableData("Fukuzo", "Moguro");
    tableDatas.add(tableData02);
    TableData tableData03 = new TableData("Mikoto", "Ohyuki");
    tableDatas.add(tableData03);
    tableView.setItems(tableDatas);
    // シーン作�
    Scene scene = new Scene(tableView);
    stage.setScene(scene);
    stage.setTitle("Table View Sample");
    stage.show();
}
Example 19
Project: pieShare-master  File: FileFilterSettingsController.java View source code
@Override
public void initialize(URL location, ResourceBundle resources) {
    buttonAdd.disableProperty().set(true);
    buttonSelectFile.setText("");
    InputStream stFile = getClass().getResourceAsStream("/images/fileIcon_24.png");
    Image imageFile = new Image(stFile);
    buttonSelectFile.setGraphic(new ImageView(imageFile));
    buttonSelectDir.setText("");
    InputStream stDir = getClass().getResourceAsStream("/images/dirIcon_24.png");
    Image imageDir = new Image(stDir);
    buttonSelectDir.setGraphic(new ImageView(imageDir));
    buttonAdd.setText("");
    InputStream stAdd = getClass().getResourceAsStream("/images/add_24.png");
    Image imageAdd = new Image(stAdd);
    buttonAdd.setGraphic(new ImageView(imageAdd));
    buttonDelete.setText("");
    InputStream stDelete = getClass().getResourceAsStream("/images/remove_24.png");
    Image imageDelete = new Image(stDelete);
    buttonDelete.setGraphic(new ImageView(imageDelete));
    listItems = FXCollections.observableArrayList();
    listViewFilters.setItems(listItems);
    listViewFilters.setCellFactory(new Callback<ListView<ITwoColumnListViewItem>, ListCell<ITwoColumnListViewItem>>() {

        @Override
        public ListCell<ITwoColumnListViewItem> call(final ListView<ITwoColumnListViewItem> param) {
            return new TwoColumnListViewEntry();
        }
    });
    listViewFilters.setOnMouseClicked(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent arg0) {
            if (listViewFilters.getSelectionModel().getSelectedItems() != null) {
                patternTextField.setText(((IFilter) listViewFilters.getSelectionModel().getSelectedItem().getObject()).getPattern());
            }
        }
    });
    refreshList();
    patternTextField.textProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> observableValue, String s, String s2) {
            //Clear all Styles. 
            patternTextField.getStyleClass().clear();
            if (patternTextField.textProperty().isEmpty().get()) {
                buttonAdd.disableProperty().set(true);
                patternTextField.getStyleClass().add("textfieldWrong");
                return;
            }
            try {
                regexService.setPattern(s2);
            } catch (Exception ex) {
                buttonAdd.disableProperty().set(true);
                patternTextField.getStyleClass().add("textfieldWrong");
                return;
            }
            patternTextField.getStyleClass().add("textfieldOK");
            buttonAdd.disableProperty().set(false);
        }
    });
}
Example 20
Project: SlideshowFX-master  File: JavaScriptSnippetExecutor.java View source code
@Override
public ObservableList<String> execute(final CodeSnippet codeSnippet) {
    final ObservableList<String> consoleOutput = FXCollections.observableArrayList();
    final Thread snippetThread = new Thread(() -> {
        final StringWriter writer = new StringWriter();
        final ScriptEngineManager manager = new ScriptEngineManager();
        final ScriptEngine engine = manager.getEngineByName("nashorn");
        engine.getContext().setWriter(writer);
        try {
            engine.eval(codeSnippet.getCode());
            consoleOutput.add(writer.toString());
        } catch (ScriptException ex) {
            consoleOutput.add(ex.getMessage());
        }
    });
    snippetThread.start();
    return consoleOutput;
}
Example 21
Project: SnakeFX-master  File: HighscoreManager.java View source code
private void updateList() {
    FXCollections.sort(highScoreEntries);
    for (int i = 0; i < highScoreEntries.size(); i++) {
        if (i < MAX_SCORE_COUNT.get()) {
            highScoreEntries.get(i).setRanking(i + 1);
        } else {
            highScoreEntries.remove(i);
        }
    }
    dao.persist(highScoreEntries);
}
Example 22
Project: speedment-master  File: TypeMapperPropertyEditor.java View source code
@Override
public Stream<Item> fieldsFor(T document) {
    final String currentValue = document.getTypeMapper().isPresent() ? document.getTypeMapper().get() : null;
    final Class<?> type = document.findDatabaseType();
    final Map<String, String> mapping = MapStream.fromStream(typeMappers.mapFrom(type),  tm -> tm.getLabel(),  tm -> tm.getClass().getName()).toSortedMap();
    final ObservableList<String> alternatives = FXCollections.observableList(mapping.keySet().stream().collect(toList()));
    alternatives.add(0, IDENTITY_MAPPER);
    //Create a binding that will convert the ChoiceBox's value to a valid
    //value for the document.typeMapperProperty()
    binding = Bindings.createStringBinding(() -> {
        if (outputValue.isEmpty().get() || outputValue.get().equals(IDENTITY_MAPPER)) {
            return null;
        } else {
            return mapping.get(outputValue.get());
        }
    }, outputValue);
    document.typeMapperProperty().bind(binding);
    outputValue.set(currentValue != null ? MapStream.of(mapping).filterValue(currentValue::equals).keys().findAny().orElseThrow(() -> new RuntimeException("Could not find requested value '" + currentValue + "' in mapping.")) : null);
    return Stream.of(new ChoiceBoxItem<String>("JDBC Type to Java", outputValue, alternatives, "The class that will be used to map types between the database and the generated code."));
}
Example 23
Project: svarog-master  File: WaveformRenderer.java View source code
public static ObservableList<XYChart.Data<Number, Number>> compute(Waveform wf, double t0, WindowType windowType, Complex coeff, double samplingFrequency) {
    double hw = wf.getHalfWidth();
    double tStart = t0 - hw, tEnd = t0 + hw;
    int iStart = (int) Math.round(tStart * samplingFrequency - 0.5);
    int iEnd = (int) Math.round(tEnd * samplingFrequency + 0.5);
    int length = (int) (1 + iEnd - iStart);
    double[] ones = new double[length];
    Arrays.fill(ones, 1.0);
    if (windowType != null) {
        ones = new WindowFunction(windowType, windowType.getParameterDefault()).applyWindow(ones);
    }
    Complex[] values = new Complex[length];
    double sumSquare = 0.0;
    for (int i = iStart; i <= iEnd; ++i) {
        double t = i / samplingFrequency;
        Complex waveformValue = wf.value(t - t0).multiply(ones[i - iStart]);
        values[i - iStart] = waveformValue;
        double re = waveformValue.getReal();
        double im = waveformValue.getImaginary();
        sumSquare += re * re + im * im;
    }
    final Complex norm = coeff.multiply(1.0 / Math.sqrt(sumSquare * samplingFrequency));
    ObservableList<XYChart.Data<Number, Number>> result = FXCollections.observableArrayList();
    for (int i = iStart; i <= iEnd; ++i) {
        double t = i / samplingFrequency;
        double value = values[i - iStart].multiply(norm).getReal();
        result.add(new XYChart.Data<Number, Number>(t, value));
    }
    return result;
}
Example 24
Project: TDMXP-master  File: MyPieChart.java View source code
protected static PieChart createChart() {
    final PieChart pc = new PieChart(FXCollections.observableArrayList(new PieChart.Data("Sun", 20), new PieChart.Data("IBM", 12), new PieChart.Data("HP", 25), new PieChart.Data("Dell", 22), new PieChart.Data("Apple", 30)));
    // setup chart
    pc.setId("BasicPie");
    pc.setTitle(title);
    return pc;
}
Example 25
Project: blackmarket-master  File: SearchResultsPane.java View source code
public void setSearchResultItems(List<ExileToolsHit> exileToolHits) {
    this.originalList = FXCollections.observableList(exileToolHits);
    if (ladder.get() != null) {
        applyDataFromLadder(ladder.get());
    }
    // add empty row
    originalList.addAll(ExileToolsHit.EMPTY, ExileToolsHit.EMPTY, ExileToolsHit.EMPTY);
    searchLabelStatus.set(format("%d items found. Showing %d items.", originalList.size() - 3, originalList.size() - 3));
    List<ExileToolsHit> list = applyOnlineOnly(onlineOnly.get());
    setItems(FXCollections.observableList(list));
}
Example 26
Project: cirqwizard-master  File: TracesSettingsPopOver.java View source code
public void refresh() {
    try {
        supressInvalidation = true;
        toolComboBox.setItems(FXCollections.observableArrayList(ToolLibrary.load().getToolSettings()));
        toolComboBox.getSelectionModel().select(context.getCurrentMillingToolIndex());
    } catch (Exception e) {
        LoggerFactory.logException("Could not load tool library", e);
    } finally {
        supressInvalidation = false;
    }
}
Example 27
Project: Corendon-master  File: LogController.java View source code
// We will call this function in a new thread, so the user can still click buttons
private void recieveData(List<LogAction> logList) {
    logFileList = logList;
    tableData = FXCollections.observableArrayList();
    for (LogAction logEntry : logFileList) {
        String formattedDate = DateUtil.formatDate("dd-MM-yyyy HH:mm:ss", logEntry.date);
        TableLog logTable = new TableLog(logEntry.getID(), logEntry.employee.username, logEntry.employee.id, logEntry.action.getName(), formattedDate);
        tableData.add(logTable);
    }
    Platform.runLater(() -> {
        logInfo.setItems(tableData);
        logTable.getChildren().remove(iconPane);
    });
}
Example 28
Project: diirt-master  File: ValueViewer.java View source code
private void enumMetadata(Object value) {
    if (value instanceof org.diirt.vtype.Enum) {
        enumMetadata.setVisible(true);
        enumMetadata.setManaged(true);
        labelsField.setItems(FXCollections.observableList(((org.diirt.vtype.Enum) value).getLabels()));
    } else {
        enumMetadata.setVisible(false);
        enumMetadata.setManaged(false);
    }
}
Example 29
Project: dwoss-master  File: ShipmentUpdateStage.java View source code
private void init(Shipment s) {
    okButton.setOnAction((ActionEvent event) -> {
        shipment = getShipment();
        if (isValid())
            close();
    });
    cancelButton.setOnAction((ActionEvent event) -> {
        close();
    });
    idField = new TextField(Long.toString(s.getId()));
    idField.setDisable(true);
    shipIdField = new TextField(s.getShipmentId());
    Callback<ListView<TradeName>, ListCell<TradeName>> cb = new Callback<ListView<TradeName>, ListCell<TradeName>>() {

        @Override
        public ListCell<TradeName> call(ListView<TradeName> param) {
            return new ListCell<TradeName>() {

                @Override
                protected void updateItem(TradeName item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty)
                        setText("Hersteller wählen...");
                    else
                        setText(item.getName());
                }
            };
        }
    };
    Set<TradeName> contractors = Client.lookup(MandatorSupporter.class).loadContractors().all();
    ownerBox = new ComboBox<>(FXCollections.observableArrayList(contractors));
    ownerBox.setMaxWidth(MAX_VALUE);
    ownerBox.setCellFactory(cb);
    ownerBox.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends TradeName> observable, TradeName oldValue, TradeName newValue) -> {
        if (newValue == null)
            return;
        shipment.setContractor(newValue);
        manufacturerBox.getSelectionModel().select(newValue.getManufacturer());
    });
    ObservableList<TradeName> manufacturers = FXCollections.observableArrayList(TradeName.getManufacturers());
    manufacturerBox = new ComboBox<>(manufacturers);
    manufacturerBox.setMaxWidth(MAX_VALUE);
    manufacturerBox.setCellFactory(cb);
    SingleSelectionModel<TradeName> sm = ownerBox.getSelectionModel();
    if (s.getContractor() == null)
        sm.selectFirst();
    else
        sm.select(s.getContractor());
    if (shipment.getDefaultManufacturer() != null)
        manufacturerBox.getSelectionModel().select(shipment.getDefaultManufacturer());
    statusBox = new ComboBox<>(FXCollections.observableArrayList(Shipment.Status.values()));
    statusBox.setMaxWidth(MAX_VALUE);
    statusBox.getSelectionModel().select(s.getStatus() == null ? OPENED : s.getStatus());
    GridPane grid = new GridPane();
    grid.addRow(1, new Label("ID:"), idField);
    grid.addRow(2, new Label("Shipment ID:"), shipIdField);
    grid.addRow(3, new Label("Besitzer:"), ownerBox);
    grid.addRow(4, new Label("Hersteller:"), manufacturerBox);
    grid.addRow(5, new Label("Status"), statusBox);
    grid.setMaxWidth(MAX_VALUE);
    grid.vgapProperty().set(2.);
    grid.getColumnConstraints().add(0, new ColumnConstraints(100, 100, Double.MAX_VALUE, Priority.SOMETIMES, HPos.LEFT, false));
    grid.getColumnConstraints().add(1, new ColumnConstraints(100, 150, Double.MAX_VALUE, Priority.ALWAYS, HPos.LEFT, true));
    HBox hButtonBox = new HBox(okButton, cancelButton);
    hButtonBox.alignmentProperty().set(Pos.TOP_RIGHT);
    errorLabel.setWrapText(true);
    BorderPane rootPane = new BorderPane(grid, errorLabel, null, hButtonBox, null);
    this.setTitle(s.getId() > 0 ? "Shipment bearbeiten" : "Shipment anlegen");
    this.setScene(new Scene(rootPane));
    this.setResizable(false);
}
Example 30
Project: geotoolkit-master  File: FXUserStyle.java View source code
@Override
public void initialize() {
    super.initialize();
    menuItems = FXCollections.observableArrayList();
    menuItems.add(new FXStyleTree.NewFTSAction());
    menuItems.add(new FXStyleTree.NewRuleAction());
    final List<FXStyleElementController> editors = FXStyleElementEditor.findEditorsForType(Symbolizer.class);
    for (FXStyleElementController editor : editors) {
        menuItems.add(new FXStyleTree.NewSymbolizerAction(editor));
    }
    menuItems.add(new SeparatorMenuItem());
    menuItems.add(new FXStyleTree.DuplicateAction());
    menuItems.add(new FXStyleTree.DeleteAction());
    FXUtilities.hideTableHeader(tree);
}
Example 31
Project: griffon-master  File: MappingObservableListTest.java View source code
@Test
public void testOperations() {
    // given:
    ObservableList<String> source = FXCollections.observableArrayList();
    Function<String, Integer> mapper = Integer::valueOf;
    ObservableList<Integer> target = new MappingObservableList<>(source, mapper);
    // expect:
    assertThat(target, empty());
    // when:
    source.addAll("1", "2", "3", "4", "5");
    // then:
    assertThat(target, contains(1, 2, 3, 4, 5));
    // when:
    source.remove("3");
    // then:
    assertThat(target, contains(1, 2, 4, 5));
    // when:
    source.remove("2");
    source.remove("4");
    // then:
    assertThat(target, contains(1, 5));
    source.set(0, "5");
    source.set(1, "1");
    // then:
    assertThat(target, contains(5, 1));
}
Example 32
Project: Illarion-Java-master  File: ChannelSelectionController.java View source code
@Override
public void initialize(URL location, @Nonnull ResourceBundle resources) {
    ObservableList<String> targets = FXCollections.observableArrayList(resources.getString("optionRelease"), resources.getString("optionSnapshot"));
    targetClient.setItems(targets);
    targetEasyNpc.setItems(targets);
    targetEasyQuest.setItems(targets);
    targetMapEditor.setItems(targets);
}
Example 33
Project: jitwatch-master  File: HistoPlotter.java View source code
private void updateObservable() {
    chart.getData().clear();
    ObservableList<XYChart.Data<Number, Number>> observableValues = FXCollections.observableArrayList();
    for (XYChart.Data<Number, Number> value : values) {
        if (value.getXValue().intValue() <= limit) {
            observableValues.add(value);
        }
    }
    XYChart.Series<Number, Number> series = new XYChart.Series<>(observableValues);
    series.setName("Method Sizes");
    chart.getData().add(series);
    for (Series<Number, Number> chartSeries : chart.getData()) {
        for (final XYChart.Data<Number, Number> data : chartSeries.getData()) {
            Tooltip tooltip = new Tooltip();
            tooltip.setText(data.getYValue().toString() + " instances of value " + data.getXValue().toString());
            Tooltip.install(data.getNode(), tooltip);
        }
    }
    chart.setTitle(getTitle());
}
Example 34
Project: KnightOfWor-master  File: HighscoreScreen.java View source code
@Override
public void start(final Stage primaryStage) {
    primaryStage.setTitle("Knight of Wor - Highscore");
    primaryStage.setResizable(false);
    GridPane grid = new GridPane();
    grid.setId("highscoreGrid");
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(30);
    grid.setVgap(30);
    final Label highscoreTitle = new Label("Highscore");
    //		highscoreTitle.setFont(new Font("Monospace", 48));
    //		highscoreTitle.setTextFill(Color.WHITE);
    String dummyname = "Horst";
    int dummypoints = 9000;
    String dummyname2 = "Klaus";
    int dummypoints2 = 8300;
    final ObservableList<HighscoreEntry> dummyData = FXCollections.observableArrayList(new HighscoreEntry(dummyname, dummypoints), new HighscoreEntry(dummyname2, dummypoints2));
    TableView highscoreTable = new TableView();
    highscoreTable.setId("highscoreTable");
    TableColumn nameCol = new TableColumn("Name");
    nameCol.setMinWidth(150);
    nameCol.setCellValueFactory(new PropertyValueFactory<HighscoreEntry, String>("name"));
    nameCol.setSortable(false);
    nameCol.setResizable(false);
    TableColumn scoreCol = new TableColumn("Punkte");
    scoreCol.setMinWidth(150);
    scoreCol.setCellValueFactory(new PropertyValueFactory<HighscoreEntry, Integer>("score"));
    scoreCol.setSortable(false);
    scoreCol.setResizable(false);
    highscoreTable.setItems(dummyData);
    highscoreTable.getColumns().addAll(nameCol, scoreCol);
    Button okBtn = new Button();
    okBtn.setText("Zurück");
    okBtn.setAlignment(Pos.CENTER);
    okBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            TitleScreen title = new TitleScreen();
            title.start(primaryStage);
        }
    });
    grid.add(highscoreTitle, 0, 0);
    grid.add(highscoreTable, 0, 1);
    grid.add(okBtn, 0, 2);
    StackPane root = new StackPane();
    root.getChildren().add(grid);
    Scene scene = new Scene(root, 1024, 740);
    scene.getStylesheets().add(TitleScreen.class.getResource("controls.css").toExternalForm());
    scene.getStylesheets().add(Credits.class.getResource("HighscoreScreen.css").toExternalForm());
    primaryStage.setScene(scene);
    primaryStage.show();
}
Example 35
Project: latexdraw-master  File: ShortcutsController.java View source code
@SuppressWarnings("unchecked")
@Override
public void initialize(URL location, ResourceBundle resources) {
    final String ctrl = KeyEvent.getKeyModifiersText(InputEvent.CTRL_MASK);
    final String shift = KeyEvent.getKeyModifiersText(InputEvent.SHIFT_MASK);
    //$NON-NLS-1$
    final String leftClick = LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.8");
    //$NON-NLS-1$
    final String catEdit = LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.89");
    //$NON-NLS-1$
    final String catNav = LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.4");
    //$NON-NLS-1$
    final String catTran = LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.5");
    //$NON-NLS-1$
    final String catDraw = LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.6");
    //$NON-NLS-1$
    final String catFile = LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.88");
    for (int i = 0, size = table.getColumns().size(); i < size; i++) {
        final int colIndex = i;
        TableColumn<ObservableList<String>, String> col = (TableColumn<ObservableList<String>, String>) table.getColumns().get(i);
        col.setCellValueFactory( cellData -> new ReadOnlyStringWrapper(cellData.getValue().get(colIndex)));
    }
    table.getColumns().forEach( col -> col.prefWidthProperty().bind(table.widthProperty().divide(3)));
    //$NON-NLS-1$
    table.getItems().addAll(//$NON-NLS-1$
    FXCollections.observableArrayList(ctrl + "+C", LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.40"), catEdit), //$NON-NLS-1$
    FXCollections.observableArrayList(ctrl + "+V", LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.43"), catEdit), //$NON-NLS-1$
    FXCollections.observableArrayList(ctrl + "+X", LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.44"), catEdit), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(ctrl + "+Z", LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.23"), catEdit), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(ctrl + "+Y", LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.22"), catEdit), //$NON-NLS-1$
    FXCollections.observableArrayList(ctrl + "+N", LangTool.INSTANCE.getBundle().getString("Res.2"), catFile), //$NON-NLS-1$
    FXCollections.observableArrayList(ctrl + "+O", LangTool.INSTANCE.getBundle().getString("FileLoaderSaver.3"), catFile), //$NON-NLS-1$
    FXCollections.observableArrayList(ctrl + "+S", LangTool.INSTANCE.getBundle().getString("FileLoaderSaver.1"), catFile), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(ctrl + "+W", LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.18"), catFile), //$NON-NLS-1$
    FXCollections.observableArrayList(KeyEvent.getKeyText(KeyEvent.VK_ADD), LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.57"), catNav), //$NON-NLS-1$
    FXCollections.observableArrayList(KeyEvent.getKeyText(KeyEvent.VK_SUBTRACT), LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.58"), catNav), //$NON-NLS-1$
    FXCollections.observableArrayList(KeyEvent.getKeyText(KeyEvent.VK_DELETE), LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.17"), catDraw), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(KeyEvent.getKeyText(KeyEvent.VK_RIGHT), LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.9"), catNav), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(KeyEvent.getKeyText(KeyEvent.VK_LEFT), LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.10"), catNav), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(KeyEvent.getKeyText(KeyEvent.VK_UP), LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.11"), catNav), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(KeyEvent.getKeyText(KeyEvent.VK_DOWN), LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.12"), catNav), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(ctrl + "+U", LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.23"), catTran), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(ctrl + "+A", LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.25"), catDraw), //$NON-NLS-1$
    FXCollections.observableArrayList(ctrl + '+' + leftClick, LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.26"), catDraw), //$NON-NLS-1$
    FXCollections.observableArrayList(shift + '+' + leftClick, LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.27"), catDraw), //$NON-NLS-1$ //$NON-NLS-2$
    FXCollections.observableArrayList(ctrl + '+' + LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.29"), LangTool.INSTANCE.getBundle().getString("ShortcutsFrame.30"), catDraw));
}
Example 36
Project: od_7guis-master  File: MainViewInitializer.java View source code
/**
	 * todo: note: two-way binding for widgets would be overkill. That's why the widget's values are initialized here
	 */
public void handleDataInitializedEvent() {
    ClientPresentationModel pm = clientDolphin.getAt(ApplicationConstants.PM_APP);
    ComboBox<Pair<String, String>> cb = mainView.flightTypeComboBox;
    cb.getItems().addAll(FXCollections.observableArrayList(pairlistFromString(SharedDolphinFunctions.stringValue(pm.getAt(ApplicationConstants.ATT_FLIGHT_TYPES)))));
    ODComboBoxes.populateFromAttribute(cb, pm.getAt(ApplicationConstants.ATT_FLIGHT_TYPE));
    ODTextFields.populateFromAttribute(mainView.startDateTextField, pm.getAt(ApplicationConstants.ATT_START_DATE));
    ODTextFields.populateFromAttribute(mainView.returnDateTextField, pm.getAt(ApplicationConstants.ATT_RETURN_DATE));
}
Example 37
Project: POL-POM-5-master  File: ExpandedListTest.java View source code
@Test
public void testListCreation() {
    ObservableList<List<String>> observableList = FXCollections.observableArrayList(Arrays.asList("11"), Arrays.asList("21", "22"), Arrays.asList());
    ExpandedList<String, List<String>> expandedList = new ExpandedList<>(observableList, Function.identity());
    List<String> actual = new ArrayList<>();
    Bindings.bindContent(actual, expandedList);
    assertEquals(3, expandedList.size());
    assertEquals("11", expandedList.get(0));
    assertEquals("21", expandedList.get(1));
    assertEquals("22", expandedList.get(2));
    assertEquals(3, actual.size());
    assertEquals("11", actual.get(0));
    assertEquals("21", actual.get(1));
    assertEquals("22", actual.get(2));
}
Example 38
Project: UFMGame-master  File: Highscores.java View source code
@FXML
private void initialize() {
    startgame.setOnMouseEntered(new EventHandler<MouseEvent>() {

        public void handle(MouseEvent me) {
            newgame.setVisible(true);
            loadgame.setVisible(true);
        }
    });
    newgame.setOnMouseEntered(new EventHandler<MouseEvent>() {

        public void handle(MouseEvent me) {
            newgame.setVisible(true);
            loadgame.setVisible(true);
        }
    });
    loadgame.setOnMouseEntered(new EventHandler<MouseEvent>() {

        public void handle(MouseEvent me) {
            newgame.setVisible(true);
            loadgame.setVisible(true);
        }
    });
    startgame.setOnMouseExited(new EventHandler<MouseEvent>() {

        public void handle(MouseEvent me) {
            newgame.setVisible(false);
            loadgame.setVisible(false);
        }
    });
    newgame.setOnMouseExited(new EventHandler<MouseEvent>() {

        public void handle(MouseEvent me) {
            newgame.setVisible(false);
            loadgame.setVisible(false);
        }
    });
    loadgame.setOnMouseExited(new EventHandler<MouseEvent>() {

        public void handle(MouseEvent me) {
            newgame.setVisible(false);
            loadgame.setVisible(false);
        }
    });
    LinkedHashMap<String, Double> result = Save.getHighscore();
    ArrayList<User> arraylistusernames = new ArrayList<User>();
    for (String key : result.keySet()) {
        Human human = new Human(new Team("test", "test", "test"), key, 5);
        human.setHighscore(result.get(key));
        arraylistusernames.add(human);
    }
    ObservableList<User> observableUsernames = FXCollections.observableArrayList(arraylistusernames);
    highscoretable.setItems(observableUsernames);
    usernames.setCellValueFactory(new PropertyValueFactory<User, String>("userName"));
    goals.setCellValueFactory(new PropertyValueFactory<User, Double>("highscore"));
    goals.setSortType(SortType.DESCENDING);
    highscoretable.getSortOrder().add(goals);
    goals.setSortable(true);
}
Example 39
Project: autopsy-master  File: Toolbar.java View source code
@FXML
@NbBundle.Messages({ "Toolbar.groupByLabel=Group By:", "Toolbar.sortByLabel=Sort By:", "Toolbar.ascRadio=Ascending", "Toolbar.descRadio=Descending", "Toolbar.tagImageViewLabel=Tag Group's Files:", "Toolbar.categoryImageViewLabel=Categorize Group's Files:", "Toolbar.thumbnailSizeLabel=Thumbnail Size (px):", "Toolbar.sortHelp=The sort direction (ascending/descending) affects the queue of unseen groups that Image Gallery maintains, but changes to this queue aren't apparent until the \"Next Unseen Group\" button is pressed.", "Toolbar.sortHelpTitle=Group Sorting" })
void initialize() {
    assert catGroupMenuButton != null : "fx:id=\"catSelectedMenubutton\" was not injected: check your FXML file 'Toolbar.fxml'.";
    assert groupByBox != null : "fx:id=\"groupByBox\" was not injected: check your FXML file 'Toolbar.fxml'.";
    assert sizeSlider != null : "fx:id=\"sizeSlider\" was not injected: check your FXML file 'Toolbar.fxml'.";
    assert tagGroupMenuButton != null : "fx:id=\"tagSelectedMenubutton\" was not injected: check your FXML file 'Toolbar.fxml'.";
    controller.viewState().addListener(( observable,  oldViewState,  newViewState) -> {
        Platform.runLater(() -> syncGroupControlsEnabledState(newViewState));
    });
    syncGroupControlsEnabledState(controller.viewState().get());
    try {
        TagGroupAction followUpGroupAction = new TagGroupAction(controller.getTagsManager().getFollowUpTagName(), controller);
        tagGroupMenuButton.setOnAction(followUpGroupAction);
        tagGroupMenuButton.setText(followUpGroupAction.getText());
        tagGroupMenuButton.setGraphic(followUpGroupAction.getGraphic());
    } catch (TskCoreException ex) {
        LOGGER.log(Level.SEVERE, "Could create follow up tag menu item", ex);
    }
    tagGroupMenuButton.showingProperty().addListener( showing -> {
        if (tagGroupMenuButton.isShowing()) {
            List<MenuItem> selTagMenues = Lists.transform(controller.getTagsManager().getNonCategoryTagNames(),  tn -> GuiUtils.createAutoAssigningMenuItem(tagGroupMenuButton, new TagGroupAction(tn, controller)));
            tagGroupMenuButton.getItems().setAll(selTagMenues);
        }
    });
    CategorizeGroupAction cat5GroupAction = new CategorizeGroupAction(Category.FIVE, controller);
    catGroupMenuButton.setOnAction(cat5GroupAction);
    catGroupMenuButton.setText(cat5GroupAction.getText());
    catGroupMenuButton.setGraphic(cat5GroupAction.getGraphic());
    catGroupMenuButton.showingProperty().addListener( showing -> {
        if (catGroupMenuButton.isShowing()) {
            List<MenuItem> categoryMenues = Lists.transform(Arrays.asList(Category.values()),  cat -> GuiUtils.createAutoAssigningMenuItem(catGroupMenuButton, new CategorizeGroupAction(cat, controller)));
            catGroupMenuButton.getItems().setAll(categoryMenues);
        }
    });
    groupByLabel.setText(Bundle.Toolbar_groupByLabel());
    tagImageViewLabel.setText(Bundle.Toolbar_tagImageViewLabel());
    categoryImageViewLabel.setText(Bundle.Toolbar_categoryImageViewLabel());
    thumbnailSizeLabel.setText(Bundle.Toolbar_thumbnailSizeLabel());
    groupByBox.setItems(FXCollections.observableList(DrawableAttribute.getGroupableAttrs()));
    groupByBox.getSelectionModel().select(DrawableAttribute.PATH);
    groupByBox.getSelectionModel().selectedItemProperty().addListener(queryInvalidationListener);
    groupByBox.disableProperty().bind(ImageGalleryController.getDefault().regroupDisabled());
    groupByBox.setCellFactory( listView -> new AttributeListCell());
    groupByBox.setButtonCell(new AttributeListCell());
    sortChooser = new SortChooser<>(GroupSortBy.getValues());
    sortChooser.comparatorProperty().addListener(( observable,  oldComparator,  newComparator) -> {
        final boolean orderEnabled = newComparator == GroupSortBy.NONE || newComparator == GroupSortBy.PRIORITY;
        sortChooser.setSortOrderDisabled(orderEnabled);
        final SortChooser.ValueType valueType = newComparator == GroupSortBy.GROUP_BY_VALUE ? SortChooser.ValueType.LEXICOGRAPHIC : SortChooser.ValueType.NUMERIC;
        sortChooser.setValueType(valueType);
        queryInvalidationListener.invalidated(observable);
    });
    sortChooser.sortOrderProperty().addListener(queryInvalidationListener);
    sortChooser.setComparator(GroupSortBy.PRIORITY);
    getItems().add(1, sortChooser);
    sortHelpImageView.setCursor(Cursor.HAND);
    sortHelpImageView.setOnMouseClicked( clicked -> {
        Text text = new Text(Bundle.Toolbar_sortHelp());
        text.setWrappingWidth(480);
        showPopoverHelp(sortHelpImageView, Bundle.Toolbar_sortHelpTitle(), sortHelpImageView.getImage(), text);
    });
}
Example 40
Project: bgfinancas-master  File: Conta.java View source code
@Override
public ObservableList<Conta> listar() {
    try {
        this.select(idCategoria, nome, valor, ativada, saldoTotal);
        if (nome.getValor() != null) {
            this.where(nome, "LIKE");
        } else if (ativada.getValor() != null) {
            this.where(ativada, "=");
        }
        this.orderByAsc(nome);
        ResultSet rs = this.query();
        if (rs != null) {
            List<Conta> Linhas = new ArrayList<>();
            while (rs.next()) {
                Linhas.add(instanciar(rs));
            }
            ObservableList<Conta> Resultado = FXCollections.observableList(Linhas);
            return Resultado;
        } else {
            return null;
        }
    } catch (SQLException ex) {
        Janela.showException(ex);
        return null;
    }
}
Example 41
Project: bikingFX-master  File: JsonRetrievalTask.java View source code
/**
     * Instantiates a new retrieval task, sets up an observable list, starts the task in a
     * separate thread and fills the list on succeeded state.
     * 
     * @param <T>
     * @param objectFactory
     * @param endpoint
     * @return 
     */
public static <T> ObservableList<T> get(final ObjectFactory<T> objectFactory, final String endpoint) {
    final ObservableList<T> rv = FXCollections.observableArrayList();
    final JsonRetrievalTask<T> bikesRetrievalTask = new JsonRetrievalTask<>(objectFactory, endpoint);
    bikesRetrievalTask.setOnSucceeded( state -> {
        rv.addAll((Collection<T>) state.getSource().getValue());
    });
    new Thread(bikesRetrievalTask).start();
    return rv;
}
Example 42
Project: bitcoin-exchange-master  File: SelectDepositTxWindow.java View source code
///////////////////////////////////////////////////////////////////////////////////////////
// Protected
///////////////////////////////////////////////////////////////////////////////////////////
private void addContent() {
    Label label = addMultilineLabel(gridPane, ++rowIndex, "The deposit transaction was not stored in the trade.\n" + "Please select one of the existing MultiSig transactions from your wallet which was the " + "deposit transaction used in the failed trade.\n\n" + "You can find the correct transaction by opening the trade details window (click on the trade ID in the list)" + " and following the offer fee payment transaction output to the next transaction where you see " + "the Multisig deposit transaction (the address starts with 3). That transaction ID should be " + "visible in the list presented here. Once you found the correct transaction select that transaction here and continue.\n\n" + "Sorry for the inconvenience but that error case should be happen very rare and in future we will try " + "to find better ways to resolve it.", 10);
    GridPane.setMargin(label, new Insets(0, 0, 10, 0));
    Tuple2<Label, ComboBox> tuple = addLabelComboBox(gridPane, ++rowIndex, "Select deposit transaction");
    transactionsComboBox = tuple.second;
    transactionsComboBox.setPromptText("Select");
    transactionsComboBox.setConverter(new StringConverter<Transaction>() {

        @Override
        public String toString(Transaction transaction) {
            return transaction.getHashAsString();
        }

        @Override
        public Transaction fromString(String string) {
            return null;
        }
    });
    transactionsComboBox.setItems(FXCollections.observableArrayList(transactions));
    transactionsComboBox.setOnAction( event -> {
        selectHandlerOptional.get().accept(transactionsComboBox.getSelectionModel().getSelectedItem());
        hide();
    });
}
Example 43
Project: bitsquare-master  File: SelectDepositTxWindow.java View source code
///////////////////////////////////////////////////////////////////////////////////////////
// Protected
///////////////////////////////////////////////////////////////////////////////////////////
private void addContent() {
    Label label = addMultilineLabel(gridPane, ++rowIndex, "The deposit transaction was not stored in the trade.\n" + "Please select one of the existing MultiSig transactions from your wallet which was the " + "deposit transaction used in the failed trade.\n\n" + "You can find the correct transaction by opening the trade details window (click on the trade ID in the list)" + " and following the offer fee payment transaction output to the next transaction where you see " + "the Multisig deposit transaction (the address starts with 3). That transaction ID should be " + "visible in the list presented here. Once you found the correct transaction select that transaction here and continue.\n\n" + "Sorry for the inconvenience but that error case should be happen very rare and in future we will try " + "to find better ways to resolve it.", 10);
    GridPane.setMargin(label, new Insets(0, 0, 10, 0));
    Tuple2<Label, ComboBox> tuple = addLabelComboBox(gridPane, ++rowIndex, "Select deposit transaction");
    transactionsComboBox = tuple.second;
    transactionsComboBox.setPromptText("Select");
    transactionsComboBox.setConverter(new StringConverter<Transaction>() {

        @Override
        public String toString(Transaction transaction) {
            return transaction.getHashAsString();
        }

        @Override
        public Transaction fromString(String string) {
            return null;
        }
    });
    transactionsComboBox.setItems(FXCollections.observableArrayList(transactions));
    transactionsComboBox.setOnAction( event -> {
        selectHandlerOptional.get().accept(transactionsComboBox.getSelectionModel().getSelectedItem());
        hide();
    });
}
Example 44
Project: Cachoeira-master  File: RelationLine.java View source code
private ObservableList<Node> initFinishStartRelationLine(TaskBar parentTaskBar, TaskBar childTaskBar) {
    DoubleBinding startXProperty = parentTaskBar.layoutXProperty().add(parentTaskBar.widthProperty()).add(12);
    DoubleBinding startYProperty = parentTaskBar.layoutYProperty().add(parentTaskBar.heightProperty().divide(2));
    DoubleBinding endXProperty = childTaskBar.layoutXProperty().subtract(12);
    DoubleBinding endYProperty = childTaskBar.layoutYProperty().add(childTaskBar.heightProperty().divide(2));
    BoundLine startLine = new BoundLine(startXProperty.subtract(12), startYProperty, startXProperty, startYProperty);
    BoundLine line1 = new BoundLine(startXProperty, startYProperty, (DoubleBinding) Bindings.when(endXProperty.greaterThanOrEqualTo(startXProperty)).then(endXProperty).otherwise(startXProperty), startYProperty);
    BoundLine line2 = new BoundLine((DoubleBinding) Bindings.when(endXProperty.greaterThanOrEqualTo(startXProperty)).then(endXProperty).otherwise(startXProperty), startYProperty, (DoubleBinding) Bindings.when(endXProperty.greaterThanOrEqualTo(startXProperty)).then(endXProperty).otherwise(startXProperty), (DoubleBinding) Bindings.when(endYProperty.greaterThan(startYProperty)).then(startYProperty.add(15.5)).otherwise(startYProperty.subtract(15.5)));
    BoundLine line3 = new BoundLine((DoubleBinding) Bindings.when(endXProperty.greaterThanOrEqualTo(startXProperty)).then(endXProperty).otherwise(startXProperty), (DoubleBinding) Bindings.when(endYProperty.greaterThan(startYProperty)).then(startYProperty.add(15.5)).otherwise(startYProperty.subtract(15.5)), endXProperty, (DoubleBinding) Bindings.when(endYProperty.greaterThan(startYProperty)).then(startYProperty.add(15.5)).otherwise(startYProperty.subtract(15.5)));
    BoundLine line4 = new BoundLine(endXProperty, (DoubleBinding) Bindings.when(endYProperty.greaterThan(startYProperty)).then(startYProperty.add(15.5)).otherwise(startYProperty.subtract(15.5)), endXProperty, endYProperty);
    BoundLine endLine = new BoundLine(endXProperty, endYProperty, endXProperty.add(12), endYProperty);
    Arrow arrow = new Arrow(endXProperty.add(12).subtract(2), endYProperty, ARROW_SHAPE);
    ObservableList<Node> relationLine = FXCollections.observableArrayList();
    relationLine.addAll(startLine, line1, line2, line3, line4, endLine, arrow);
    return relationLine;
}
Example 45
Project: CloudTrailViewer-master  File: ChartBarStackedWidgetController.java View source code
public void finishedLoading(boolean reload) {
    if (reload) {
        chart.getData().clear();
    }
    xAxis.setLabel(widget.getSeriesField());
    xAxis.setCategories(FXCollections.observableArrayList(categories));
    yAxis.setLabel("Count");
    for (Map.Entry<String, Map<String, List<Event>>> entry : multiSeries.entrySet()) {
        String seriesName = entry.getKey();
        XYChart.Series<String, Number> series = new XYChart.Series<>();
        series.setName(seriesName);
        Map<String, List<Event>> catData = entry.getValue();
        for (Map.Entry<String, List<Event>> data : catData.entrySet()) {
            String catName = data.getKey();
            List<Event> events = data.getValue();
            series.getData().add(new XYChart.Data<>(catName, events.size()));
        }
        chart.getData().add(series);
    }
    for (XYChart.Series<String, Number> series : chart.getData()) {
        for (XYChart.Data<String, Number> item : series.getData()) {
            String seriesName = series.getName();
            Map<String, List<Event>> catData = multiSeries.get(seriesName);
            for (Map.Entry<String, List<Event>> catData2 : catData.entrySet()) {
                List<Event> events = catData2.getValue();
                item.getNode().setOnMousePressed((MouseEvent event) -> eventTableService.setTableEvents(events));
                Node node = item.getNode();
                Tooltip t = new Tooltip(seriesName + " : " + item.getYValue());
                Tooltip.install(node, t);
            }
        }
    }
}
Example 46
Project: EclipseDay-Presentation-master  File: PieChartView.java View source code
/**
     * This is a callback that will allow us to create the viewer and initialize it.
     */
@Override
public void createPartControl(final Composite parent) {
    this.canvas = new FXCanvas(parent, SWT.NONE);
    final BorderPane root = new BorderPane();
    final Scene scene = new Scene(root, 800, 600, Color.WHITE);
    this.canvas.setScene(scene);
    final PieChart pc = new PieChart();
    // setup chart
    pc.setTitle("Top 5 Systèmes d'exploitation - Janvier 2012 - France");
    pc.setLegendSide(Side.RIGHT);
    pc.setAnimated(true);
    pc.setLabelLineLength(30);
    pc.setStartAngle(180);
    root.setCenter(pc);
    final List<PieChart.Data> dataList = new ArrayList<>();
    dataList.add(new PieChart.Data("Win7", 44.67));
    dataList.add(new PieChart.Data("WinXP", 23.05));
    dataList.add(new PieChart.Data("Win Vista", 17.68));
    dataList.add(new PieChart.Data("MacOSX", 10.38));
    dataList.add(new PieChart.Data("Linux", 1.95));
    final List<PieChart.Data> dataList2 = new ArrayList<>();
    dataList2.add(new PieChart.Data("Win7", 44.67));
    dataList2.add(new PieChart.Data("WinXP", 23.05));
    dataList2.add(new PieChart.Data("Win Vista", 17.68));
    dataList2.add(new PieChart.Data("MacOSX", 10.38));
    dataList2.add(new PieChart.Data("Linux", 1.95));
    final ObservableList<PieChart.Data> data = FXCollections.observableArrayList(dataList);
    final EventHandler<ActionEvent> removeLast = new EventHandler<ActionEvent>() {

        @Override
        public void handle(final ActionEvent t) {
            data.remove(data.size() - 1);
        }
    };
    final EventHandler<ActionEvent> addNext = new EventHandler<ActionEvent>() {

        @Override
        public void handle(final ActionEvent t) {
            data.add(dataList2.get(data.size()));
        }
    };
    final Timeline loading = new Timeline();
    loading.getKeyFrames().addAll(new KeyFrame(Duration.millis(500), new KeyValue(pc.dataProperty(), data)), new KeyFrame(Duration.millis(2000), removeLast), new KeyFrame(Duration.millis(2500), removeLast), new KeyFrame(Duration.millis(3000), removeLast), new KeyFrame(Duration.millis(3500), removeLast), new KeyFrame(Duration.millis(4000), removeLast), new KeyFrame(Duration.millis(4500), addNext), new KeyFrame(Duration.millis(5000), addNext), new KeyFrame(Duration.millis(5500), addNext), new KeyFrame(Duration.millis(6000), addNext), new KeyFrame(Duration.millis(6500), addNext));
    loading.play();
}
Example 47
Project: FXForm2-master  File: DefaultElementProvider.java View source code
protected <T> ListProperty<Element> createElements(final ObjectProperty<T> source) {
    ListProperty<Element> elements = new SimpleListProperty<Element>(FXCollections.<Element>observableArrayList());
    List<Field> fields = applyFilters(extractFields(source.get()));
    // Create elements for the resulting field list
    for (Field field : fields) {
        try {
            final Element element = elementFactory.create(field);
            element.sourceProperty().bind(new ObjectBinding() {

                {
                    bind(source);
                }

                @Override
                protected Object computeValue() {
                    if (source.get() != null && source.get() instanceof MultipleBeanSource) {
                        MultipleBeanSource multipleBeanSource = (MultipleBeanSource) source.get();
                        return multipleBeanSource.getSource(element);
                    }
                    return source.get();
                }
            });
            if (element.getType() != null) {
                elements.add(element);
            }
        } catch (FormException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
        }
    }
    return elements;
}
Example 48
Project: gcexplorer-master  File: ProcessViewForm.java View source code
@Override
public void initialize(URL location, ResourceBundle resources) {
    configureChart(chtEdenSpace);
    configureChart(chtSurvivorSpace);
    configureChart(chtOldGenSpace);
    configureChart(chtPermGenSpace);
    configureChart(chtStackedAreaTotalMemory);
    chtEdenSpace.setData(app.getProcessController().getEdenSeries(procId));
    chtSurvivorSpace.setData(app.getProcessController().getSurvivorSeries(procId));
    chtOldGenSpace.setData(app.getProcessController().getOldGenSeries(procId));
    chtPermGenSpace.setData(app.getProcessController().getPermGenSeries(procId));
    ((NumberAxis) chtStackedAreaTotalMemory.getYAxis()).setForceZeroInRange(true);
    chtStackedAreaTotalMemory.setData(app.getProcessController().getStackedAreaChartSeries(procId));
    this.xAxisCategory.setCategories(FXCollections.<String>observableArrayList(Arrays.asList("Total")));
    this.chtStackedBarTotalMemory.setData(app.getProcessController().getStackedBarChartSeries(procId));
    configureChart(chtStackedBarTotalMemory);
    HBox.setHgrow(gridPane, Priority.ALWAYS);
    ((NumberAxis) this.chtStackedBarTotalMemory.getYAxis()).setTickLabelFormatter(new NumberStringConverter(NumberFormat.getIntegerInstance()));
    this.updateYAxii(app.getUnits());
    btnGenerateGarbageOptions.setOnAction(this::showGarbageOptionsForm);
    app.getProcessController().addSystemInfoEventListener(procId, new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (oldValue == null || !oldValue.equals(newValue)) {
                Platform.runLater(new Runnable() {

                    @Override
                    public void run() {
                        lblSysInfo.setText(newValue);
                    }
                });
            }
        }
    });
    btnViewGCLog.setOnAction(this::showGCLogView);
    app.getProcessController().addGCInfoEventListener(procId, new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (oldValue == null || !oldValue.equals(newValue)) {
                Platform.runLater(new Runnable() {

                    @Override
                    public void run() {
                        lblGCInfo.setText(newValue);
                    }
                });
            }
        }
    });
    lblSysInfo.setText("Updating...");
    lblGCInfo.setText("Updating...");
}
Example 49
Project: graniteds-master  File: JavaFXProperty.java View source code
@SuppressWarnings("unchecked")
@Override
public void setValue(Object instance, Object value, boolean convert) {
    try {
        Class<?> fieldType = field.getType();
        Object convertedValue = value;
        if (WritableValue.class.isAssignableFrom(fieldType)) {
            WritableValue<Object> writableValue = (WritableValue<Object>) field.get(instance);
            if (writableValue instanceof WritableListValue) {
                if (value instanceof PersistentBag)
                    convertedValue = FXPersistentCollections.observablePersistentBag((PersistentBag<Object>) value);
                else if (value instanceof PersistentList)
                    convertedValue = FXPersistentCollections.observablePersistentList((PersistentList<Object>) value);
                else
                    convertedValue = FXCollections.observableList((List<Object>) value);
            } else if (writableValue instanceof WritableSetValue) {
                if (value instanceof PersistentSortedSet)
                    convertedValue = FXPersistentCollections.observablePersistentSortedSet((PersistentSortedSet<Object>) value);
                else if (value instanceof PersistentSet)
                    convertedValue = FXPersistentCollections.observablePersistentSet((PersistentSet<Object>) value);
                else
                    convertedValue = FXCollections.observableSet((Set<Object>) value);
            } else if (writableValue instanceof WritableMapValue) {
                if (value instanceof PersistentSortedMap)
                    convertedValue = FXPersistentCollections.observablePersistentSortedMap((PersistentSortedMap<Object, Object>) value);
                else if (value instanceof PersistentMap)
                    convertedValue = FXPersistentCollections.observablePersistentMap((PersistentMap<Object, Object>) value);
                else
                    convertedValue = FXCollections.observableMap((Map<Object, Object>) value);
            } else
                convertedValue = convert ? convert(value) : value;
            writableValue.setValue(convertedValue);
        } else {
            convertedValue = convert ? convert(value) : value;
            field.set(instance, convertedValue);
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not set value of property " + field, e);
    }
}
Example 50
Project: graniteds_java_client_attic-master  File: JavaFXProperty.java View source code
@SuppressWarnings("unchecked")
@Override
public void setProperty(Object instance, Object value, boolean convert) {
    try {
        Class<?> fieldType = field.getType();
        Object convertedValue = value;
        if (WritableValue.class.isAssignableFrom(fieldType)) {
            WritableValue<Object> writableValue = (WritableValue<Object>) field.get(instance);
            if (writableValue instanceof WritableListValue) {
                if (value instanceof PersistentBag)
                    convertedValue = FXPersistentCollections.observablePersistentBag((PersistentBag<Object>) value);
                else if (value instanceof PersistentList)
                    convertedValue = FXPersistentCollections.observablePersistentList((PersistentList<Object>) value);
                else
                    convertedValue = FXCollections.observableList((List<Object>) value);
            } else if (writableValue instanceof WritableSetValue) {
                if (value instanceof PersistentSortedSet)
                    convertedValue = FXPersistentCollections.observablePersistentSortedSet((PersistentSortedSet<Object>) value);
                else if (value instanceof PersistentSet)
                    convertedValue = FXPersistentCollections.observablePersistentSet((PersistentSet<Object>) value);
                else
                    convertedValue = FXCollections.observableSet((Set<Object>) value);
            } else if (writableValue instanceof WritableMapValue) {
                if (value instanceof PersistentSortedMap)
                    convertedValue = FXPersistentCollections.observablePersistentSortedMap((PersistentSortedMap<Object, Object>) value);
                else if (value instanceof PersistentMap)
                    convertedValue = FXPersistentCollections.observablePersistentMap((PersistentMap<Object, Object>) value);
                else
                    convertedValue = FXCollections.observableMap((Map<Object, Object>) value);
            } else
                convertedValue = convert ? convert(value) : value;
            writableValue.setValue(convertedValue);
        } else {
            convertedValue = convert ? convert(value) : value;
            field.set(instance, convertedValue);
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not set value of property " + field, e);
    }
}
Example 51
Project: HotSUploader-master  File: FXUtils.java View source code
@Override
public void handle(KeyEvent event) {
    switch(event.getCode()) {
        case DOWN:
            if (!comboBox.isShowing()) {
                comboBox.show();
            }
        case UP:
            caretPos = -1;
            moveCaret(comboBox.getEditor().getText().length());
            return;
        case BACK_SPACE:
        case DELETE:
            moveCaretToPos = true;
            caretPos = comboBox.getEditor().getCaretPosition();
            break;
    }
    if (KeyCode.RIGHT == event.getCode() || KeyCode.LEFT == event.getCode() || event.isControlDown() || KeyCode.HOME == event.getCode() || KeyCode.END == event.getCode() || KeyCode.TAB == event.getCode()) {
        return;
    }
    final ObservableList<T> list = FXCollections.observableArrayList();
    for (T aData : data) {
        if (shouldDataBeAddedToInput(aData)) {
            list.add(aData);
        }
    }
    final String text = comboBox.getEditor().getText();
    comboBox.setItems(list);
    comboBox.getEditor().setText(text);
    if (!moveCaretToPos) {
        caretPos = -1;
    }
    moveCaret(text.length());
    if (!list.isEmpty()) {
        comboBox.show();
    }
}
Example 52
Project: idnadrev-master  File: ManagePostsController.java View source code
@Override
public void onResume() {
    List<GravBlog> blogs = PersistentWork.from(GravBlog.class);
    controller.getJavaFXExecutor().submit(() -> {
        SingleSelectionModel<GravBlog> selectionModel = blogSelection.getSelectionModel();
        GravBlog selectedItem = selectionModel.getSelectedItem();
        blogSelection.setItems(FXCollections.observableList(blogs));
        if (blogs.size() > 0) {
            if (selectedItem != null) {
                selectionModel.select(selectedItem);
            } else {
                selectionModel.select(0);
            }
        }
    });
}
Example 53
Project: jfxtras-master  File: AllAppointmentsTest.java View source code
@Test
public void regularAppointment1() {
    // just an appointment somewhere on a day
    ObservableList<Agenda.Appointment> lAppointments = FXCollections.observableArrayList(new Agenda.AppointmentImplLocal().withStartLocalDateTime(LocalDateTime.of(2014, 1, 2, 8, 00)).withEndLocalDateTime(LocalDateTime.of(2014, 1, 2, 11, 30)));
    AllAppointments lAllAppointments = new AllAppointments(lAppointments);
    Assert.assertEquals(0, lAllAppointments.collectRegularFor(LocalDate.of(2014, 1, 1)).size());
    Assert.assertEquals(1, lAllAppointments.collectRegularFor(LocalDate.of(2014, 1, 2)).size());
    Assert.assertEquals(0, lAllAppointments.collectRegularFor(LocalDate.of(2014, 1, 3)).size());
    // others
    Assert.assertEquals(0, lAllAppointments.collectWholedayFor(LocalDate.of(2014, 1, 2)).size());
    Assert.assertEquals(0, lAllAppointments.collectTaskFor(LocalDate.of(2014, 1, 2)).size());
}
Example 54
Project: JRebirth-master  File: SlideMenuView.java View source code
/**
     * {@inheritDoc}
     */
@Override
protected void initView() {
    getRootNode().setPrefSize(600, 600);
    getRootNode().setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
    getRootNode().setMinSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
    final ObservableList<Slide> items = FXCollections.observableArrayList(getModel().getSlides());
    getRootNode().setItems(items);
    getRootNode().getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
    getRootNode().getSelectionModel().select(getModel().getObject());
    getRootNode().scrollTo(getModel().getObject());
    getRootNode().getSelectionModel().selectedItemProperty().addListener((final ObservableValue<? extends Slide> ov, final Slide old_val, final Slide new_val) -> {
        getModel().callCommand(ShowSlideCommand.class, Builders.waveData(PrezWaves.SLIDE, new_val));
        ((Pane) getRootNode().getParent()).getChildren().remove(getRootNode());
    });
    getRootNode().setCellFactory( list -> {
        return new ListCell<Slide>() {

            @Override
            public void updateItem(final Slide item, final boolean empty) {
                super.updateItem(item, empty);
                if (item == null) {
                    setText(null);
                } else {
                    setText(item.getPage() + ". " + item.getTitle());
                }
            }
        };
    });
}
Example 55
Project: jvarkit-master  File: VariantTypeChartFactory.java View source code
@Override
public Chart build() {
    final ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
    for (int i = 0; i < categories.length; ++i) {
        if (counts[i] == 0)
            continue;
        pieChartData.add(new PieChart.Data(categories[i].getName() + " " + counts[i], counts[i]));
    }
    final PieChart chart = new PieChart(pieChartData);
    chart.setTitle(this.getName());
    chart.setLegendVisible(false);
    return chart;
}
Example 56
Project: LIMO-master  File: DataEntryTableModel.java View source code
@Override
protected ObservableList<XYChart.Series> getBarChartData() {
    ObservableList<XYChart.Series> bcData = FXCollections.<BarChart.Series>observableArrayList();
    List<Integer> activeIndexes = new ArrayList<>();
    for (int i = 1; i < enabled.size(); i++) {
        if (enabled.get(i) == true) {
            activeIndexes.add(i);
        }
    }
    activeIndexes.stream().map(( activeIndexe) -> {
        XYChart.Series serie = new XYChart.Series();
        ObservableList<XYChart.Data> dataSet = FXCollections.<BarChart.Data>observableArrayList();
        for (int j = 1; j < getRowCount(); j++) {
            XYChart.Data data = new XYChart.Data();
            data.setXValue(names.get(j - 1));
            data.setYValue(getValueAt(j, activeIndexe));
            dataSet.add(data);
        }
        serie.setData(dataSet);
        serie.setName(getColumnName(activeIndexe));
        return serie;
    }).forEach(( serie) -> {
        bcData.add(serie);
    });
    return bcData;
}
Example 57
Project: mavenize-master  File: DataViewTest.java View source code
@SuppressWarnings("unchecked")
@Override
public void start(Stage stage) {
    observableList = FXCollections.synchronizedObservableList(FXCollections.observableList(new LinkedList<ServiceResult>()));
    resultService = new ResultService(observableList, this);
    Button refreshBtn = new Button("Update");
    refreshBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            resultService.reset();
            resultService.start();
        }
    });
    Button clearBtn = new Button("Clear");
    clearBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            observableList.clear();
        }
    });
    TableColumn<ServiceResult, String> nameCol = new TableColumn<ServiceResult, String>("Value");
    nameCol.setCellValueFactory(new PropertyValueFactory<ServiceResult, String>("value"));
    nameCol.setPrefWidth(200);
    dataTable.getColumns().setAll(nameCol);
    // productTable.getItems().addAll(products);
    dataTable.setItems(observableList);
    Scene scene = new Scene(new Group());
    stage.setTitle("Table View Sample");
    stage.setWidth(300);
    stage.setHeight(500);
    final VBox vOuterBox = new VBox();
    vOuterBox.setSpacing(5);
    final HBox hbox = new HBox();
    hbox.setSpacing(5);
    hbox.setPadding(new Insets(10, 0, 0, 10));
    hbox.getChildren().addAll(refreshBtn, clearBtn);
    final VBox vbox = new VBox();
    vbox.setSpacing(5);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(dataTable);
    vOuterBox.getChildren().addAll(hbox, vbox);
    ((Group) scene.getRoot()).getChildren().addAll(vOuterBox);
    stage.setScene(scene);
    stage.show();
}
Example 58
Project: mzmine3-master  File: MsSpectrumLayersDialogController.java View source code
public void initialize() {
    final ObservableList<MsSpectrumType> renderingChoices = FXCollections.observableArrayList(MsSpectrumType.CENTROIDED, MsSpectrumType.PROFILE);
    renderingTypeColumn.setCellFactory(ChoiceBoxTableCell.forTableColumn(renderingChoices));
    colorColumn.setCellFactory( column -> new ColorTableCell<MsSpectrumDataSet>(column));
    lineThicknessColumn.setCellFactory( column -> new SpinnerTableCell<MsSpectrumDataSet>(column, 1, 5));
    intensityScaleColumn.setCellFactory(TextFieldTableCell.forTableColumn(new NumberStringConverter(MZmineCore.getConfiguration().getIntensityFormat())));
    showDataPointsColumn.setCellFactory( column -> new CheckBoxTableCell<MsSpectrumDataSet, Boolean>() {

        {
            tableRowProperty().addListener( e -> {
                TableRow<?> row = getTableRow();
                if (row == null)
                    return;
                MsSpectrumDataSet dataSet = (MsSpectrumDataSet) row.getItem();
                if (dataSet == null)
                    return;
                disableProperty().bind(dataSet.renderingTypeProperty().isEqualTo(MsSpectrumType.CENTROIDED));
            });
        }
    });
}
Example 59
Project: sportstracker-master  File: SamplePanelController.java View source code
@Override
protected void setupPanel() {
    // setup table columns
    tcTime.setCellValueFactory(new PropertyValueFactory<>("timestamp"));
    tcHeartrate.setCellValueFactory(new PropertyValueFactory<>("heartRate"));
    tcAltitude.setCellValueFactory(new PropertyValueFactory<>("altitude"));
    tcSpeed.setCellValueFactory(new PropertyValueFactory<>("speed"));
    tcDistance.setCellValueFactory(new PropertyValueFactory<>("distance"));
    tcCadence.setCellValueFactory(new PropertyValueFactory<>("cadence"));
    tcTemperature.setCellValueFactory(new PropertyValueFactory<>("temperature"));
    // setup custom number cell factories for all table columns
    final RecordingMode recordingMode = getDocument().getExercise().getRecordingMode();
    tcTime.setCellFactory(new FormattedNumberCellFactory<>( value -> getContext().getFormatUtils().seconds2TimeString(value.intValue() / 1000)));
    tcHeartrate.setCellFactory(new FormattedNumberCellFactory<>( value -> getContext().getFormatUtils().heartRateToString(value.intValue())));
    tcAltitude.setCellFactory(new FormattedNumberCellFactory<>( value -> recordingMode.isAltitude() ? getContext().getFormatUtils().heightToString(value.intValue()) : null));
    tcSpeed.setCellFactory(new FormattedNumberCellFactory<>( value -> recordingMode.isSpeed() ? getContext().getFormatUtils().speedToString(value.floatValue(), 2) : null));
    tcDistance.setCellFactory(new FormattedNumberCellFactory<>( value -> recordingMode.isSpeed() ? getContext().getFormatUtils().distanceToString(value.doubleValue() / 1000d, 3) : null));
    tcCadence.setCellFactory(new FormattedNumberCellFactory<>( value -> recordingMode.isCadence() ? getContext().getFormatUtils().cadenceToString(value.intValue()) : null));
    tcTemperature.setCellFactory(new FormattedNumberCellFactory<>( value -> recordingMode.isTemperature() ? getContext().getFormatUtils().temperatureToString(value.shortValue()) : null));
    // set table data
    tvSamples.setPlaceholder(new Label(getContext().getResources().getString("pv.info.no_data_available")));
    final ExerciseSample[] samples = getDocument().getExercise().getSampleList();
    tvSamples.setItems(FXCollections.observableArrayList(samples == null ? new ExerciseSample[0] : samples));
    // default sort is the time column
    tvSamples.getSortOrder().add(tcTime);
}
Example 60
Project: spring-framework-issues-master  File: SearchController.java View source code
@FXML
public void initialize() {
    orderId.setCellValueFactory(new PropertyValueFactory<OrderTableRow, Integer>("orderId"));
    orderId.setCellFactory(new FormattedTableCellFactory<OrderTableRow, Integer>(Pos.CENTER_RIGHT));
    customerId.setCellValueFactory(new PropertyValueFactory<OrderTableRow, Integer>("customerId"));
    customerId.setCellFactory(new FormattedTableCellFactory<OrderTableRow, Integer>(Pos.CENTER_RIGHT));
    productsCount.setCellValueFactory(new PropertyValueFactory<OrderTableRow, Integer>("products"));
    productsCount.setCellFactory(new FormattedTableCellFactory<OrderTableRow, Integer>(Pos.CENTER_RIGHT));
    delivered.setCellValueFactory(new PropertyValueFactory<OrderTableRow, Boolean>("delivered"));
    delivered.setCellFactory(new FormattedTableCellFactory<OrderTableRow, Boolean>(Pos.CENTER));
    deliveryDays.setCellValueFactory(new PropertyValueFactory<OrderTableRow, Integer>("deliveryDays"));
    deliveryDays.setCellFactory(new FormattedTableCellFactory<OrderTableRow, Integer>(Pos.CENTER_RIGHT));
    totalOrderPrice.setCellValueFactory(new PropertyValueFactory<OrderTableRow, Integer>("total"));
    totalOrderPrice.setCellFactory(new FormattedTableCellFactory<OrderTableRow, Integer>(Pos.CENTER_RIGHT));
    List<Order> orders = orderService.findAllOrders();
    ObservableList<OrderTableRow> orderRows = FXCollections.observableArrayList();
    for (Order order : orders) {
        orderRows.add(new OrderTableRow(order));
    }
    table.setItems(orderRows);
}
Example 61
Project: tablesaw-master  File: FxPareto.java View source code
public static BarChart<String, Number> chart(String title, CategoryColumn x, NumericColumn y) {
    final CategoryAxis xAxis = new CategoryAxis();
    final NumberAxis yAxis = new NumberAxis();
    xAxis.setLabel(x.name());
    yAxis.setLabel(y.name());
    Table t = Table.create("", x, y);
    t = t.sortDescendingOn(y.name());
    final BarChart<String, Number> bar = new BarChart<>(xAxis, yAxis);
    bar.setTitle(title);
    List<XYChart.Data<String, Number>> d2 = new ArrayList<>(x.size());
    for (int i = 0; i < x.size(); i++) {
        d2.add(new XYChart.Data<>(t.categoryColumn(0).get(i), t.nCol(1).getFloat(i)));
    }
    XYChart.Series<String, Number> series1 = new XYChart.Series<>(FXCollections.observableList(d2));
    series1.setName(y.name());
    bar.setLegendVisible(false);
    bar.setCategoryGap(0.0);
    bar.setBarGap(0.1);
    bar.setBackground(Background.EMPTY);
    bar.setVerticalGridLinesVisible(false);
    bar.getData().addAll(series1);
    return bar;
}
Example 62
Project: URL-pad-master  File: UtilsTest.java View source code
/**
     * Test of convertToObservableList method, of class Utils.
     */
@Test
public void testConvertToObservableListValid() {
    // given:
    HashSet<Integer> aHashSetObj = new HashSet<Integer>();
    aHashSetObj.add(1);
    aHashSetObj.add(2);
    ObservableList expResult = FXCollections.observableArrayList();
    expResult.add(1);
    expResult.add(2);
    // when:
    ObservableList result = Utils.convertToObservableList(aHashSetObj);
    // then:
    assertEquals(expResult, result);
    assertEquals(expResult.size(), result.size());
    assertEquals(expResult.get(0), result.get(0));
    assertEquals(expResult.get(1), result.get(1));
}
Example 63
Project: VickyWarAnalyzer-master  File: WarListController.java View source code
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 64
Project: viskell-master  File: GraphBlock.java View source code
@Override
public void invalidateVisualState() {
    this.input.invalidateVisualState();
    if (!(this.inValidContext && this.input.hasValidConnection())) {
        return;
    }
    ObservableList<XYChart.Series<Double, Double>> lineChartData = FXCollections.observableArrayList();
    double step = 0.01;
    double min = x.getLowerBound();
    double max = x.getUpperBound();
    try {
        GhciSession ghciSession = getToplevel().getGhciSession();
        String funName = "graph_fun_" + Integer.toHexString(this.hashCode());
        ghciSession.push(funName, this.getAllInputs().get(0).getFullExpr());
        String range = String.format(Locale.US, " [%f,%f..%f]", min, min + step, max);
        String results = ghciSession.pullRaw("putStrLn $ unwords $ map show $ map " + funName + range).get();
        LineChart.Series<Double, Double> series = new LineChart.Series<>();
        ObservableList<XYChart.Data<Double, Double>> data = series.getData();
        Iterator<String> v = Splitter.on(' ').split(results).iterator();
        for (double i = min; i < max; i += step) {
            data.add(new XYChart.Data<>(i, Double.valueOf(v.next())));
        }
        lineChartData.add(series);
    } catch (NoSuchElementExceptionNumberFormatException | InterruptedException | ExecutionException |  ignored) {
    }
    chart.setData(lineChartData);
}
Example 65
Project: AsciidocFX-master  File: AsciidoctorConfigBase.java View source code
@Override
public void load(ActionEvent... actionEvent) {
    infoLabel.setText("Loading...");
    Reader fileReader = IOHelper.fileReader(getConfigPath());
    JsonReader jsonReader = Json.createReader(fileReader);
    JsonObject jsonObject = jsonReader.readObject();
    String safe = jsonObject.getString("safe", "safe");
    boolean sourcemap = jsonObject.getBoolean("sourcemap", false);
    String backend = jsonObject.getString("backend", null);
    boolean header_footer = jsonObject.getBoolean("header_footer", false);
    JsonObject attributes = jsonObject.getJsonObject("attributes");
    String jsPlatform = jsonObject.getString("jsPlatform", "Webkit");
    IOHelper.close(jsonReader, fileReader);
    threadService.runActionLater(() -> {
        this.setSafe(safe);
        this.sourcemap.set(sourcemap);
        this.setBackend(backend);
        this.setHeader_footer(header_footer);
        this.setJsPlatform(JSPlatform.valueOf(JSPlatform.class, jsPlatform));
        ObservableList<AttributesTable> attrList = FXCollections.observableArrayList();
        if (Objects.nonNull(attributes)) {
            for (Map.Entry<String, JsonValue> attr : attributes.entrySet()) {
                AttributesTable attributesTable = new AttributesTable();
                attributesTable.setAttribute(attr.getKey());
                attributesTable.setValue(((JsonString) attr.getValue()).getString());
                attrList.add(attributesTable);
            }
        }
        setAttributes(attrList);
        fadeOut(infoLabel, "Loaded...");
    });
}
Example 66
Project: chunky-master  File: SceneChooserController.java View source code
private void populateSceneTable(File sceneDir) {
    List<JsonObject> scenes = new ArrayList<>();
    List<File> fileList = SceneHelper.getAvailableSceneFiles(sceneDir);
    Collections.sort(fileList);
    for (File sceneFile : fileList) {
        String fileName = sceneFile.getName();
        try {
            JsonParser parser = new JsonParser(new FileInputStream(new File(sceneDir, fileName)));
            JsonObject scene = parser.parse().object();
            // The scene name and filename may not always match. This can happen
            // if the user has copied and renamed some scene file.
            // Therefore we make sure to distinguish scenes by filename.
            scene.add("fileName", fileName.substring(0, fileName.length() - Scene.EXTENSION.length()));
            scenes.add(scene);
        } catch (IOExceptionJsonParser.SyntaxError |  e) {
            Log.warnf("Warning: could not load scene description: %s", fileName);
        }
    }
    sceneTbl.setItems(FXCollections.observableArrayList(scenes));
    if (!scenes.isEmpty()) {
        sceneTbl.getSelectionModel().select(0);
    }
}
Example 67
Project: ColloidUI-master  File: MainController.java View source code
@Override
public void initialize(URL location, ResourceBundle resources) {
    //disable peer radio - p2p
    isPeer.setDisable(true);
    if (recountApp.isRunning()) {
        parseActButton.setText("Stop");
    }
    textLog.setEditable(false);
    recountLog.setEditable(false);
    ObservableList<Actor> items = FXCollections.observableArrayList();
    combatListView.setItems(items);
    ObservableList<String> logItems = FXCollections.observableArrayList();
    textLog.setItems(logItems);
    recountApp.onUpdate(new Combat.EventHandler<CombatEvent>() {

        @Override
        public void handle(CombatEvent event) {
            treeView.setRoot(Util.rootTreeView(recountApp.getFightList()));
        }
    });
}
Example 68
Project: examples-javafx-repos1-master  File: PreferencesController.java View source code
@FXML
public void browse(ActionEvent evt) {
    if (logger.isDebugEnabled()) {
        logger.debug("[BROWSE]");
    }
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Select JARs");
    fileChooser.getExtensionFilters().addAll(new ExtensionFilter("JAR Files", "*.jar", "*.zip"));
    List<File> selectedFiles = fileChooser.showOpenMultipleDialog(((Button) evt.getSource()).getScene().getWindow());
    if (selectedFiles != null) {
        lvJARs.getItems().clear();
        lvJARs.setItems(FXCollections.observableArrayList(selectedFiles));
    }
}
Example 69
Project: ISAAC-master  File: ObservableConceptChronologyImpl.java View source code
//~--- methods -------------------------------------------------------------
/**
    * Concept description list property.
    *
    * @return the list property
    */
@Override
public ListProperty<ObservableSememeChronology<ObservableDescriptionSememe<?>>> conceptDescriptionListProperty() {
    if (this.descriptionListProperty == null) {
        final ObservableList<ObservableSememeChronology<ObservableDescriptionSememe<?>>> observableList = FXCollections.observableArrayList();
        this.descriptionListProperty = new SimpleListProperty<>(this, ObservableFields.DESCRIPTION_LIST_FOR_CONCEPT.toExternalString(), observableList);
        this.chronicledObjectLocal.getConceptDescriptionList().stream().forEach(( conceptDescriptionChronicle) -> {
            final ObservableSememeChronologyImpl observableConceptDescriptionChronicle = new ObservableSememeChronologyImpl(conceptDescriptionChronicle);
            observableList.add(observableConceptDescriptionChronicle);
        });
    }
    return this.descriptionListProperty;
}
Example 70
Project: JacpFX-misc-master  File: ContactChartViewComponent.java View source code
private void refreshChartPane(final Contact contact) {
    this.root.getChildren().clear();
    this.bc = this.createChart();
    this.root.getChildren().add(this.bc);
    this.bc.setTitle(contact.getFirstName() + " " + contact.getLastName() + " consumer Chart");
    this.xAxis.setCategories(FXCollections.<String>observableArrayList(Arrays.asList(Util.YEARS)));
}
Example 71
Project: JavaFX-HelpMaker-master  File: MainController.java View source code
public void onTreeViewClick() {
    XMLNodeItemExtended justSelectedNode = ((TreeItem<XMLNodeItemExtended>) XMLTreeView.getFocusModel().getFocusedItem()).getValue();
    if ((justSelectedNode != null) && (currentSelectedXMLNodeItemExtended != justSelectedNode)) {
        saveHTMLFile();
        currentSelectedXMLNodeItemExtended = justSelectedNode;
        parameters.remove(0, parameters.size());
        parameters = FXCollections.observableArrayList(currentSelectedXMLNodeItemExtended.getParameters());
        XMLNodeParameters.setItems(parameters);
        readFileToHTMLEditor(currentSelectedXMLNodeItemExtended.getParameterValueByKey(XMLParameter.PARAMETER_ID));
    }
}
Example 72
Project: JFoenix-master  File: RecursiveTreeItem.java View source code
private void addChildrenListener(RecursiveTreeObject<T> value) {
    final ObservableList<T> children = childrenFactory.call(value);
    originalItems = FXCollections.observableArrayList();
    for (T child : children) {
        originalItems.add(new RecursiveTreeItem<>(child, getGraphic(), childrenFactory));
    }
    filteredItems = new FilteredList<>(originalItems, (TreeItem<T> t) -> true);
    this.getChildren().addAll(originalItems);
    children.addListener((ListChangeListener<T>)  change -> {
        while (change.next()) {
            if (change.wasAdded()) {
                change.getAddedSubList().forEach( t -> {
                    RecursiveTreeItem<T> newItem = new RecursiveTreeItem<>(t, getGraphic(), childrenFactory);
                    RecursiveTreeItem.this.getChildren().add(newItem);
                    originalItems.add(newItem);
                });
            }
            if (change.wasRemoved()) {
                change.getRemoved().forEach( t -> {
                    for (int i = 0; i < RecursiveTreeItem.this.getChildren().size(); i++) {
                        if (this.getChildren().get(i).getValue().equals(t)) {
                            originalItems.remove(this.getChildren().remove(i));
                            i--;
                        }
                    }
                });
            }
        }
    });
}
Example 73
Project: jidefx-oss-master  File: FontPopupContent.java View source code
private void initializeComponents(Font font) {
    // create components
    BorderPane previewPanel = new BorderPane();
    previewPanel.setBorder(new Border(new BorderStroke(Color.GRAY, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(1))));
    _previewLabel = new Label(getResourceString("preview"));
    _previewLabel.setPrefSize(210, 60);
    _previewLabel.setAlignment(Pos.CENTER);
    _previewLabel.setFont(font);
    previewPanel.setCenter(_previewLabel);
    _fontFamilyComboBox = new ComboBox<>();
    LazyLoadUtils.install(_fontFamilyComboBox, new Callback<ComboBox<String>, ObservableList<String>>() {

        @Override
        public ObservableList<String> call(ComboBox<String> comboBox) {
            return FXCollections.observableArrayList(Font.getFamilies());
        }
    });
    // Without setting it, it will come up with a small size then expand when setItems is called
    _fontFamilyComboBox.setPrefWidth(160);
    new ComboBoxSearchable<>(_fontFamilyComboBox);
    DecimalFormat integerFormat = (DecimalFormat) DecimalFormat.getNumberInstance();
    integerFormat.setMaximumIntegerDigits(3);
    integerFormat.setMaximumFractionDigits(1);
    _sizeSpinner = new NumberField();
    _sizeSpinner.setDecimalFormat(integerFormat);
    _sizeSpinner.setSpinnersVisible(true);
    _sizeSpinner.setValue(font.getSize());
    _styleChoiceBox = new ChoiceBox<>();
    // layout components
    MigPane content = (MigPane) getContent();
    //NON-NLS
    content.add(previewPanel, new CC().grow().span(2).wrap().gapBottom("6px"));
    content.add(new Label(getResourceString("font")));
    content.add(_fontFamilyComboBox, new CC().wrap());
    Label sizeLabel = new Label(getResourceString("size"));
    content.add(sizeLabel);
    //NON-NLS
    content.add(_sizeSpinner, new CC().split().maxWidth("60px").wrap());
    _sizeSpinner.installAdjustmentMouseHandler(sizeLabel);
    content.add(new Label(getResourceString("style")));
    content.add(_styleChoiceBox, new CC().grow().wrap());
}
Example 74
Project: LifeTiles-master  File: SequenceController.java View source code
/**
     * Generate Sequence entries from sequences and store them.
     *
     * @param sequences
     *            the sequences
     */
// suppress a false positive on SequenceEntry
@SuppressFBWarnings("DLS_DEAD_LOCAL_STORE")
private void initializeEntries(final Map<String, Sequence> sequences) {
    sequenceEntries = FXCollections.observableHashMap();
    for (Sequence sequence : sequences.values()) {
        SequenceEntry sequenceEntry = SequenceEntry.fromSequence(sequence);
        String identifier = sequence.getIdentifier();
        if (identifier.equals(DEFAULT_REFERENCE)) {
            sequenceEntry = SequenceEntry.fromSequence(sequence, true, true);
            reference = identifier;
            shout(SequenceController.REFERENCE_SET, "", sequence);
        } else {
            sequenceEntry = SequenceEntry.fromSequence(sequence);
        }
        addVisibilityListener(sequenceEntry);
        addReferenceListener(sequenceEntry);
        sequenceEntries.put(identifier, sequenceEntry);
    }
}
Example 75
Project: lightfish-master  File: DashboardPresenter.java View source code
@Override
public void initialize(URL url, ResourceBundle rb) {
    this.snapshots = FXCollections.observableArrayList();
    this.pools = FXCollections.observableHashMap();
    this.escalationsPresenter = new EscalationsPresenter(this.dashboardModel.serverUriProperty());
    this.usedHeapSizeInMB = new SimpleLongProperty();
    this.threadCount = new SimpleLongProperty();
    this.peakThreadCount = new SimpleIntegerProperty();
    this.busyThreads = new SimpleIntegerProperty();
    this.queuedConnections = new SimpleIntegerProperty();
    this.commitCount = new SimpleIntegerProperty();
    this.rollbackCount = new SimpleIntegerProperty();
    this.totalErrors = new SimpleIntegerProperty();
    this.activeSessions = new SimpleIntegerProperty();
    this.expiredSessions = new SimpleIntegerProperty();
    this.id = new SimpleLongProperty();
    this.commitsPerSecond = new SimpleDoubleProperty();
    this.rollbacksPerSecond = new SimpleDoubleProperty();
    this.deadlockedThreads = new SimpleStringProperty();
    this.initializeListeners();
}
Example 76
Project: Manga-Library-master  File: MangaLibraryCtrl.java View source code
private void addManga(String name, List<String> chapters) {
    ListView<String> content = new ListView<>(FXCollections.observableArrayList(chapters));
    content.getSelectionModel().selectedItemProperty().addListener(( obs,  oldVal,  newVal) -> this.<MangaViewCtrl>setMain("manga-view.fxml").setManga(name).setChapter(newVal, false));
    // TODO Load that value, default to -1
    SimpleIntegerProperty readMarkerIndex = new SimpleIntegerProperty(-1);
    content.getSelectionModel().selectedIndexProperty().addListener(( obs,  oldVal,  newVal) -> {
        if (newVal.intValue() > readMarkerIndex.get()) {
            // TODO Save the new value
            readMarkerIndex.setValue(newVal);
        }
    });
    content.setCellFactory( listView -> new MarkableTextFieldListCell(readMarkerIndex, "read-marker"));
    TitledPane pane = new TitledPane(name, content);
    pane.setFont(new Font(15));
    accordion.getPanes().add(pane);
}
Example 77
Project: mytime-master  File: ChooseLokationController.java View source code
private void setAllLocationsAsItems() {
    try {
        ObservableList items = FXCollections.observableArrayList();
        items.addAll(model.getAllLocations());
        comboBoxLocation.setItems(items);
    } catch (SQLException ex) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Couldn't get a connection to the database");
        alert.setContentText("Check your internet connection, and make you you are connected properly\nErrorcode: " + ex.getMessage());
        alert.show();
    }
}
Example 78
Project: performance-test-harness-for-geoevent-master  File: ReportOptionsController.java View source code
private void updateSelectedReportColumns(List<String> selectedColumnsList) {
    List<String> currentSelection = selectedColumnsList;
    if (currentSelection == null || currentSelection.size() == 0) {
        currentSelection = new ArrayList<String>(AbstractFileRollOverReportWriter.getDefaultColumnNames());
    }
    // remove all items from the all list
    List<String> allColumnsList = new ArrayList<String>(AbstractFileRollOverReportWriter.getAllColumnNames());
    allColumnsList.removeAll(currentSelection);
    allColumns.setItems(FXCollections.observableList(allColumnsList));
    // update the selected list
    selectedColumns.setItems(FXCollections.observableList(currentSelection));
}
Example 79
Project: RadialFx-master  File: DemoUtil.java View source code
public void addGraphicControl(final String title, final ObjectProperty<Node> graphicProperty) {
    final Node circle = CircleBuilder.create().radius(4).fill(Color.ORANGE).build();
    final Node square = RectangleBuilder.create().width(8).height(8).build();
    final Node text = TextBuilder.create().text("test").build();
    final ComboBox<Node> choices = new ComboBox<Node>(FXCollections.observableArrayList(circle, square, text));
    choices.setCellFactory(new Callback<ListView<Node>, ListCell<Node>>() {

        @Override
        public ListCell<Node> call(final ListView<Node> param) {
            final ListCell<Node> cell = new ListCell<Node>() {

                @Override
                public void updateItem(final Node item, final boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null) {
                        setText(item.getClass().getSimpleName());
                    } else {
                        setText(null);
                    }
                }
            };
            return cell;
        }
    });
    choices.getSelectionModel().select(0);
    graphicProperty.bind(choices.valueProperty());
    final VBox box = new VBox();
    final Text titleText = new Text(title);
    titleText.textProperty().bind(new StringBinding() {

        {
            super.bind(choices.selectionModelProperty());
        }

        @Override
        protected String computeValue() {
            return title + " : " + String.valueOf(choices.selectionModelProperty().get().getSelectedItem().getClass().getSimpleName());
        }
    });
    box.getChildren().addAll(titleText, choices);
    getChildren().add(box);
}
Example 80
Project: simelec-master  File: MainForm.java View source code
public void initialize(URL location, ResourceBundle resources) {
    cbxResidents.setItems(FXCollections.observableArrayList(1, 2, 3, 4, 5));
    cbxMonth.setItems(FXCollections.observableArrayList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"));
    cbxDayOfWeek.setItems(FXCollections.observableArrayList("Weekday", "Weekend"));
    cbxResidents.setValue(1);
    cbxMonth.setValue("January");
    cbxDayOfWeek.setValue("Weekday");
    statusText = new SimpleStringProperty("");
    lblStatus.textProperty().bind(statusText);
    /*
		 * Make sure that "total" options grey out when the models are turned
		 * off
		 */
    chbLighting.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent arg0) {
            chbLightTotals.setDisable(!chbLighting.isSelected());
        }
    });
    chbAppliances.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent arg0) {
            chbApplianceTotals.setDisable(!chbAppliances.isSelected());
        }
    });
    Label menuLabel = new Label("About");
    menuLabel.setStyle("-fx-padding: 0px;");
    menuLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {

        public void handle(MouseEvent event) {
            Stage myDialog = new Stage();
            myDialog.initModality(Modality.WINDOW_MODAL);
            try {
                AboutUI about = new AboutUI();
                about.start(myDialog);
                myDialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    Menu fileMenuButton = new Menu();
    fileMenuButton.setGraphic(menuLabel);
    menuBar.getMenus().add(fileMenuButton);
    btnOutdir.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent e) {
            DirectoryChooser dirChooser = new DirectoryChooser();
            File home = new File(System.getProperty("user.home"));
            dirChooser.setInitialDirectory(home);
            File selectedDir = dirChooser.showDialog(stage);
            if (selectedDir != null)
                txfOutdir.setText(selectedDir.getAbsolutePath());
        }
    });
    btnRunSimElec.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent e) {
            final int residents = cbxResidents.getValue();
            String strMonth = cbxMonth.getValue();
            Calendar cal = Calendar.getInstance();
            try {
                cal.setTime(new SimpleDateFormat("MMM").parse(strMonth));
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
            final int month = cal.get(Calendar.MONTH) + 1;
            final boolean weekend = cbxDayOfWeek.getValue().equals("Weekend");
            final String out_dir = txfOutdir.getText();
            if (out_dir == null || out_dir.equals("")) {
                lblStatus.setTextFill(Color.RED);
                lblStatus.setText("Please select an output directory");
            } else {
                lblStatus.setTextFill(Color.BLACK);
                Task<Void> task = new Task<Void>() {

                    @Override
                    protected Void call() throws Exception {
                        updateMessage("Starting model run...");
                        SimElec model = new SimElec(month, residents, weekend, out_dir);
                        boolean runLighting = chbLighting.isSelected();
                        boolean runAppliances = chbAppliances.isSelected();
                        boolean runRPlots = chbRPlots.isSelected();
                        model.setRunAppliances(runAppliances);
                        model.setRunLighting(runLighting);
                        model.setCalculateGrandTotals(chbGrandTotals.isSelected());
                        boolean Rdisabled = false;
                        if (!runAppliances && !runLighting && runRPlots) {
                            runRPlots = false;
                            Rdisabled = true;
                        }
                        model.setMakeRPlots(runRPlots);
                        model.setLightingTotalsOnly(chbLightTotals.isSelected());
                        model.setAppliancesTotalsOnly(chbApplianceTotals.isSelected());
                        try {
                            model.run();
                        } catch (IOException io) {
                            io.printStackTrace();
                        }
                        String msg = Rdisabled ? "Occupancy model complete.\nNo R results." : "Simulation models complete.";
                        updateMessage(msg);
                        return null;
                    }
                };
                lblStatus.textProperty().bind(task.messageProperty());
                Thread thread = new Thread(task);
                thread.setDaemon(true);
                thread.start();
            }
        }
    });
}
Example 81
Project: thundernetwork-master  File: BitcoinUIModel.java View source code
public void update() {
    Platform.runLater(() -> {
        balance.set(Main.bitcoin.wallet().getBalance(Wallet.BalanceType.AVAILABLE_SPENDABLE));
        address.set(Main.bitcoin.wallet().currentReceiveAddress());
        ObservableList<Node> items0 = FXCollections.observableArrayList();
        for (Transaction p : Main.bitcoin.wallet().getTransactionsByTime()) {
            Label label = new Label(p.toString());
            items0.add(label);
        }
        transactionsThunderIncluded.setAll(items0);
        ObservableList<Node> items1 = FXCollections.observableArrayList();
        for (PaymentWrapper p : Main.dbHandler.getAllPayments()) {
            Label label = new Label(p.toString());
            items1.add(label);
        }
        transactionsThunderIncluded.setAll(items1);
        ObservableList<Node> items2 = FXCollections.observableArrayList();
        for (PaymentWrapper p : Main.dbHandler.getRedeemedPayments()) {
            Label label = new Label(p.toString());
            items2.add(label);
        }
        transactionsThunderSettled.setAll(items2);
        ObservableList<Node> items3 = FXCollections.observableArrayList();
        for (PaymentWrapper p : Main.dbHandler.getRefundedPayments()) {
            Label label = new Label(p.toString());
            items3.add(label);
        }
        transactionsThunderRefunded.setAll(items3);
        ObservableList<Node> items4 = FXCollections.observableArrayList();
        for (PaymentWrapper p : Main.dbHandler.getOpenPayments()) {
            Label label = new Label(p.toString());
            items4.add(label);
        }
        transactionsThunderOpen.setAll(items4);
        ObservableList<PubkeyIPObject> items5 = FXCollections.observableArrayList();
        for (PubkeyIPObject p : Main.dbHandler.getIPObjects()) {
            items5.add(p);
        }
        ipList.setAll(items5);
        ObservableList<Node> items6 = FXCollections.observableArrayList();
        for (ChannelStatusObject p : Main.dbHandler.getTopology()) {
            Label label = new Label(p.toString());
            items6.add(label);
        }
        channelNetworkList.setAll(items6);
        long totalAmount = 0;
        ObservableList<Channel> items7 = FXCollections.observableArrayList();
        for (Channel p : Main.dbHandler.getOpenChannel()) {
            totalAmount += p.channelStatus.amountServer;
            items7.add(p);
        }
        balanceThunder.set(Coin.valueOf(totalAmount));
        channelList.setAll(items7);
    });
}
Example 82
Project: webcam-capture-master  File: WebCamPreviewController.java View source code
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
    fpBottomPane.setDisable(true);
    ObservableList<WebCamInfo> options = FXCollections.observableArrayList();
    int webCamCounter = 0;
    for (Webcam webcam : Webcam.getWebcams()) {
        WebCamInfo webCamInfo = new WebCamInfo();
        webCamInfo.setWebCamIndex(webCamCounter);
        webCamInfo.setWebCamName(webcam.getName());
        options.add(webCamInfo);
        webCamCounter++;
    }
    cbCameraOptions.setItems(options);
    cbCameraOptions.setPromptText(cameraListPromptText);
    cbCameraOptions.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<WebCamInfo>() {

        @Override
        public void changed(ObservableValue<? extends WebCamInfo> arg0, WebCamInfo arg1, WebCamInfo arg2) {
            if (arg2 != null) {
                System.out.println("WebCam Index: " + arg2.getWebCamIndex() + ": WebCam Name:" + arg2.getWebCamName());
                initializeWebCam(arg2.getWebCamIndex());
            }
        }
    });
    Platform.runLater(new Runnable() {

        @Override
        public void run() {
            setImageViewSize();
        }
    });
}
Example 83
Project: wikokit-master  File: WCTranslation.java View source code
/** Creates a translation part of word card, it corresponds to one meaning.
     *
     * @return true if there are any translations in this translation block.
    **/
public boolean create(Connect conn, TTranslation _ttranslation, TLang _lang) {
    meaning_summary = _ttranslation.getMeaningSummary();
    TTranslationEntry[] trans_entries = TTranslationEntry.getByTranslation(conn, _ttranslation);
    // System.out.println("WCTranslation.create() _lang=" + _lang.getLanguage().toString() + "; trans_entries.length=" + trans_entries);
    List<TranslationEntryItem> data_trans = new ArrayList();
    //  listview_trans.items length =" + trans_entries.length);
    trans_entry_items_size = trans_entries.length;
    //trans_entry_items = new TranslationEntryItem[trans_entries.length];
    for (int i = 0; i < trans_entries.length; i++) {
        TTranslationEntry e = trans_entries[i];
        LanguageType l = e.getLang().getLanguage();
        String lang_name_value = l.getName();
        String lang_code_value = l.getCode();
        String translation_text = e.getWikiText().getText();
        TranslationEntryItem item = new TranslationEntryItem();
        item.create(lang_name_value, lang_code_value, translation_text);
        data_trans.add(item);
    }
    //  TranslationEntryItem[] trans_entry_items = data_trans.toArray();
    //insert trans_entry_items into listview_trans.items;
    ObservableList<TranslationEntryItem> data = FXCollections.observableArrayList(data_trans);
    listview_trans.setCellFactory(new Callback<ListView<wiwordik.word_card.TranslationEntryItem>, ListCell<wiwordik.word_card.TranslationEntryItem>>() {

        @Override
        public ListCell<wiwordik.word_card.TranslationEntryItem> call(ListView<wiwordik.word_card.TranslationEntryItem> list) {
            return new wiwordik.word_card.TranslationCell();
        }
    });
    listview_trans.setItems(data);
    setMinMaxTranslationBoxHeight(listview_trans, data.size());
    // GUI                          right - indent for translation list words
    //                          top right bottom left
    group.setPadding(new Insets(0, 20, 0, 0));
    Text t_meaning_summary = new Text();
    t_meaning_summary.setText(meaning_summary);
    group.getChildren().addAll(t_meaning_summary);
    group.getChildren().addAll(listview_trans);
    return trans_entries.length > 0;
}
Example 84
Project: CaseTracker-master  File: EditCaseController.java View source code
public void initialize() {
    logger.info("Initiating");
    ObservableList<Staff> inspectors = FXCollections.observableArrayList(editorService.getInspectors());
    cmbInvestigatingOfficer.setItems(inspectors);
    if (editorService.getUser().getPermission() == Permission.EDITOR) {
        cmbInvestigatingOfficer.setValue(editorService.getUser());
    }
    ObservableList<String> caseTypes = FXCollections.observableArrayList(editorService.getCaseTypes());
    cmbCaseType.setItems(caseTypes);
    cbxIsReturnVisit.selectedProperty().addListener(( obs,  oldValue,  newValue) -> {
        dpkReturnDate.setDisable(!newValue);
    });
    txfAddress.textProperty().addListener(( obs,  oldValue,  newValue) -> {
        if (newValue == null || newValue.isEmpty()) {
            txfLongitude.setDisable(false);
            txfLatitude.setDisable(false);
        } else {
            txfLongitude.setDisable(true);
            txfLatitude.setDisable(true);
        }
    });
    txfLongitude.textProperty().addListener(( obs,  oldValue,  newValue) -> {
        String latitude = txfLatitude.getText();
        if (newValue == null || newValue.isEmpty()) {
            if (latitude == null || latitude.isEmpty()) {
                txfAddress.setDisable(false);
            }
        } else {
            txfAddress.setDisable(true);
        }
    });
    txfLatitude.textProperty().addListener(( obs,  oldValue,  newValue) -> {
        String longitude = txfLongitude.getText();
        if (newValue == null || newValue.isEmpty()) {
            if (longitude == null || longitude.isEmpty()) {
                txfAddress.setDisable(false);
            }
        } else {
            txfAddress.setDisable(true);
        }
    });
    updateButton.setOnAction( event -> {
        updateCase();
    });
    populateFields();
}
Example 85
Project: CausticSDK-master  File: LibraryItemPaneController.java View source code
public void handleSearchByKey(ListView<LibraryItemProxy> list, String oldVal, String newVal) {
    // it must be because the user pressed delete
    if (oldVal != null && (newVal.length() < oldVal.length())) {
        // Restore the lists original set of entries
        // and start from the beginning
        list.setItems(FXCollections.observableArrayList(getItems(libraryModel.getSelectedKind())));
    }
    // Break out all of the parts of theO search text
    // by splitting on white space
    String[] parts = newVal.toUpperCase().split(" ");
    // Filter out the entries that don't contain the entered text
    ObservableList<LibraryItemProxy> subentries = FXCollections.observableArrayList();
    for (LibraryItemProxy entry : list.getItems()) {
        boolean match = true;
        // String entryText = (String)entry.getItem().getMetadataInfo().getTagsString();
        String entryText = (String) entry.getItem().toString();
        for (String part : parts) {
            // search string *but* in any order
            if (!entryText.toUpperCase().contains(part)) {
                match = false;
                break;
            }
        }
        if (match) {
            subentries.add(entry);
        }
    }
    list.setItems(subentries);
}
Example 86
Project: code-of-gotham-master  File: WelcomeController.java View source code
private void loadProjects() {
    // Load Projects in separate UI thread
    new Thread(() -> {
        setIsDataOrCityLoading(true);
        try {
            sonarService.setSonarSettings(sonarHostname.getText(), usernameField.getText(), passwordTextField.getText(), proxy.getText());
            try {
                projects = sonarService.getProjects();
                if (projects.isEmpty()) {
                    showAlert(AlertType.WARNING, PROJECT_LIST_EMPTY_HEAER, String.format(PROJECT_LIST_EMPTY_CONTENT, sonarHostname.getText()));
                }
                Platform.runLater(() -> projectTable.setItems(FXCollections.observableArrayList(projects)));
            } catch (SonarException e) {
                showAlert(AlertType.ERROR, PROJECTS_LOAD_ERROR_HEADER, String.format(PROJECTS_LOAD_ERROR_CONTENT, sonarHostname.getText()));
            }
        } catch (SonarException e) {
            showAlert(AlertType.ERROR, PROXY_FORM_ERROR_HEADER, String.format(PROXY_FORM_ERROR_CONTENT, proxy.getText()));
            setIsDataOrCityLoading(false);
        }
        setIsDataOrCityLoading(false);
    }).start();
}
Example 87
Project: DesktopWidget-master  File: WidgetLoaderImpl.java View source code
@Override
public ObservableMap<String, Widget> loadWidgets(File widgetDir, String filePattern, Stage containerStage, ClassLoader parentClassLoader) {
    ObservableMap<String, Widget> widgetMap = FXCollections.observableMap(new HashMap<String, Widget>());
    File[] widgets = null;
    if (widgetDir.exists()) {
        widgets = widgetDir.listFiles((FilenameFilter) ( dir,  name) -> {
            Pattern p = Pattern.compile(filePattern);
            Matcher m = p.matcher(name);
            return m.matches();
        });
        if (widgets != null && widgets.length > 0) {
            for (File widget1 : widgets) {
                System.out.println(widget1.getName());
                Widget widget = loadFile(widget1, containerStage, this.getClass().getClassLoader());
                if (widget == null) {
                    continue;
                }
                widgetMap.put(widget1.getName(), widget);
                System.out.println("loaded: " + widget1.getName());
            }
        }
    } else {
        widgetDir.mkdirs();
    }
    return widgetMap;
}
Example 88
Project: dolphin-java-demo-master  File: LazyLoadingView.java View source code
@Override
public void start(Stage stage) throws Exception {
    List<String> attributeNames = Arrays.asList(ID, FIRST_LAST, LAST_FIRST, CITY, PHONE);
    final ClientPresentationModel dataMold = dolphin.presentationModel("dataMold", attributeNames);
    final ObservableList<Map> observableList = FXCollections.observableArrayList();
    final Radial gauge = new Radial(new StyleModel());
    gauge.getStyleModel().setFrameDesign(Gauge.FrameDesign.CHROME);
    gauge.setTitle("Real Load %");
    gauge.setLcdDecimals(3);
    gauge.setPrefSize(250, 250);
    gauge.setEffect(DropShadowBuilder.create().radius(20).color(new Color(0, 0, 0, 0.4)).build());
    TableColumn<Map, String> nameCol = new TableColumn<Map, String>();
    nameCol.setText("Name");
    nameCol.setPrefWidth(150);
    // sorting needs all data to be loaded
    nameCol.setSortable(false);
    TableColumn<Map, String> cityCol = new TableColumn<Map, String>();
    cityCol.setText("City");
    cityCol.setPrefWidth(150);
    // sorting needs all data to be loaded
    cityCol.setSortable(false);
    TableView<Map> table = new TableView<Map>();
    table.setPrefWidth(300);
    table.getColumns().add(nameCol);
    table.getColumns().add(cityCol);
    table.setItems(observableList);
    // cell values are lazily requested from JavaFX and must return an observable value
    nameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map, String>, ObservableValue<String>>() {

        @Override
        public ObservableValue<String> call(TableColumn.CellDataFeatures cellDataFeatures) {
            Map valueMap = (Map) cellDataFeatures.getValue();
            // it.value['id'];
            String lazyId = valueMap.get("id").toString();
            final SimpleStringProperty placeholder = new SimpleStringProperty("...");
            dolphin.getClientModelStore().withPresentationModel(lazyId, new WithPresentationModelHandler() {

                public void onFinished(ClientPresentationModel presentationModel) {
                    String value = presentationModel.getAt(LAST_FIRST).getValue().toString();
                    // fill async lazily
                    placeholder.setValue(value);
                }
            });
            return placeholder;
        }
    });
    cityCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map, String>, ObservableValue<String>>() {

        @Override
        public ObservableValue<String> call(TableColumn.CellDataFeatures cellDataFeatures) {
            Map valueMap = (Map) cellDataFeatures.getValue();
            String lazyId = valueMap.get("id").toString();
            final SimpleStringProperty placeholder = new SimpleStringProperty("...");
            dolphin.getClientModelStore().withPresentationModel(lazyId, new WithPresentationModelHandler() {

                public void onFinished(ClientPresentationModel presentationModel) {
                    String value = presentationModel.getAt(CITY).getValue().toString();
                    // fill async lazily
                    placeholder.setValue(value);
                }
            });
            return placeholder;
        }
    });
    // when a table row is selected, we fill the mold and the detail view gets updated
    table.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Map>() {

        @Override
        public void changed(ObservableValue<? extends Map> selected, Map o, Map oldVal) {
            Map selectedPm = selected.getValue();
            String pmId = (selectedPm == null) ? null : selectedPm.get("id").toString();
            dolphin.getClientModelStore().withPresentationModel(pmId, new WithPresentationModelHandler() {

                public void onFinished(ClientPresentationModel presentationModel) {
                    dolphin.apply(presentationModel).to(dataMold);
                }
            });
        }
    });
    final TextField nameField = new TextField();
    final TextField cityField = new TextField();
    final TextField phoneField = new TextField();
    final Label lazilyLoadedField = new Label();
    final Label tableSizeField = new Label();
    final Label selectedIndexField = new Label();
    GridPane centerView = GridPaneBuilder.create().hgap(10).vgap(10).padding(new Insets(20, 20, 20, 20)).build();
    centerView.getColumnConstraints().add(ColumnConstraintsBuilder.create().halignment(HPos.RIGHT).build());
    centerView.add(new Label("Name"), 0, 0);
    centerView.add(nameField, 1, 0);
    centerView.add(new Label("City"), 0, 1);
    centerView.add(cityField, 1, 1);
    centerView.add(new Label("Phone"), 0, 2);
    centerView.add(phoneField, 1, 2);
    centerView.add(new Label("table size"), 0, 3);
    centerView.add(tableSizeField, 1, 3);
    centerView.add(new Label("lazily loaded"), 0, 4);
    centerView.add(lazilyLoadedField, 1, 4);
    centerView.add(new Label("selected index"), 0, 5);
    centerView.add(selectedIndexField, 1, 5);
    centerView.add(gauge, 1, 6);
    // all the bindings ...
    JFXBinder.bind(ID).of(dataMold).to(FX.TEXT).of(selectedIndexField);
    JFXBinder.bind(FIRST_LAST).of(dataMold).to(FX.TEXT).of(nameField);
    JFXBinder.bind(CITY).of(dataMold).to(FX.TEXT).of(cityField);
    JFXBinder.bind(PHONE).of(dataMold).to(FX.TEXT).of(phoneField);
    // count the number of lazily loaded pms by listing to the model store
    final Counter counter = new Counter();
    dolphin.addModelStoreListener(LAZY, new ModelStoreListener() {

        public void modelStoreChanged(ModelStoreEvent evt) {
            if (evt.getType() == ModelStoreEvent.Type.ADDED) {
                counter.increment();
                lazilyLoadedField.setText(String.valueOf(counter.getValue()));
            }
        }
    });
    // count the number of lazily loaded pms by listing to the model store
    dolphin.addModelStoreListener(LAZY, new ModelStoreListener() {

        public void modelStoreChanged(ModelStoreEvent evt) {
            if (evt.getType() == ModelStoreEvent.Type.ADDED) {
                gauge.setValue(100d * counter.getValue() / observableList.size());
            }
        }
    });
    // when starting, first fill the table with pm ids
    dolphin.send("fullDataRequest", new OnFinishedHandlerAdapter() {

        @Override
        public void onFinishedData(List<Map> data) {
            for (Map map : data) {
                observableList.add(map);
            }
            tableSizeField.setText(String.valueOf(observableList.size()));
        }
    });
    // TODO set margins of 10
    BorderPane borderPane = new BorderPane();
    borderPane.setLeft(table);
    borderPane.setCenter(centerView);
    Scene scene = new Scene(borderPane, 700, 500);
    defaultStyle(scene);
    stage.setScene(scene);
    stage.setTitle("Dolphin lazy loading demo");
    stage.show();
}
Example 89
Project: ewidgetfx-master  File: WidgetLoaderImpl.java View source code
@Override
public ObservableMap<String, Widget> loadWidgets(File widgetDir, String filePattern, Stage containerStage, ClassLoader parentClassLoader) {
    ObservableMap<String, Widget> widgetMap = FXCollections.observableMap(new HashMap<String, Widget>());
    File[] widgets = null;
    if (widgetDir.exists()) {
        widgets = widgetDir.listFiles((FilenameFilter) ( dir,  name) -> {
            Pattern p = Pattern.compile(filePattern);
            Matcher m = p.matcher(name);
            return m.matches();
        });
        if (widgets != null && widgets.length > 0) {
            for (File widget1 : widgets) {
                System.out.println(widget1.getName());
                Widget widget = loadFile(widget1, containerStage, this.getClass().getClassLoader());
                if (widget == null) {
                    continue;
                }
                widgetMap.put(widget1.getName(), widget);
                System.out.println("loaded: " + widget1.getName());
            }
        }
    } else {
        widgetDir.mkdirs();
    }
    return widgetMap;
}
Example 90
Project: FaceOSC-Computer-Control-master  File: KeyPresserController.java View source code
@Override
public void handle(ActionEvent e) {
    String tekst = newField.getText();
    if (!tekst.isEmpty()) {
        presser.addConf(new KeyPressConfiguration(tekst));
        configurationPicker.setItems(FXCollections.observableArrayList(presser.getConfNames()));
        configurationPicker.getSelectionModel().select(presser.getConfNames().size() - 1);
        presser.setCurrent(presser.getConfNames().size() - 1);
        newField.setText("");
        clearAll();
    }
}
Example 91
Project: FxProjects-master  File: CubeNode.java View source code
final void arrangeFacesZOrder() {
    rearFace.zPos.setValue(CubeFace.radius * Math.cos(Math.toRadians(angleY.getValue() + 0)));
    bottomFace.zPos.setValue(CubeFace.radius * Math.cos(Math.toRadians(angleX.getValue() + 270)));
    leftFace.zPos.setValue(CubeFace.radius * Math.cos(Math.toRadians(angleY.getValue() + 270)));
    rightFace.zPos.setValue(CubeFace.radius * Math.cos(Math.toRadians(angleY.getValue() + 90)));
    topFace.zPos.setValue(CubeFace.radius * Math.cos(Math.toRadians(angleX.getValue() + 90)));
    frontFace.zPos.setValue(CubeFace.radius * Math.cos(Math.toRadians(angleY.getValue() + 180)));
    FXCollections.sort(getChildren(), new CubeFaceComparator());
}
Example 92
Project: igv-master  File: PreferenceEditorFX.java View source code
private static void initFX(final JDialog parent, JFXPanel fxPanel, List<PreferencesManager.PreferenceGroup> preferenceGroups) {
    // final Map<String, String> updatedPrefs = new HashMap<>();
    TabPane tabPane = new TabPane();
    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(tabPane);
    Scene scene = new Scene(borderPane);
    Map<String, Map<String, String>> updatedPreferencesMap = new HashMap<>();
    for (PreferencesManager.PreferenceGroup entry : preferenceGroups) {
        if (entry.tabLabel.equals("Hidden"))
            continue;
        final IGVPreferences preferences = PreferencesManager.getPreferences(entry.category);
        final Map<String, String> updatedPrefs = updatedPreferencesMap.containsKey(entry.category) ? updatedPreferencesMap.get(entry.category) : new HashMap<>();
        updatedPreferencesMap.put(entry.category, updatedPrefs);
        final String tabLabel = entry.tabLabel;
        Tab tab = new Tab(tabLabel);
        tab.setClosable(false);
        tabPane.getTabs().add(tab);
        ScrollPane scrollPane = new ScrollPane();
        tab.setContent(scrollPane);
        VBox vBox = new VBox();
        vBox.setFillWidth(true);
        //   vBox.prefWidthProperty().bind(pane.widthProperty());
        scrollPane.setContent(vBox);
        GridPane gridPane = new GridPane();
        gridPane.setHgap(5);
        gridPane.setVgap(5);
        vBox.getChildren().add(gridPane);
        String currentGroup = null;
        int row = 1;
        for (PreferencesManager.Preference pref : entry.preferences) {
            try {
                Tooltip tooltip = pref.getComment() == null ? null : new Tooltip(pref.getComment());
                if (pref.getKey().equals(PreferencesManager.SEPARATOR_KEY)) {
                    Separator sep = new Separator();
                    GridPane.setColumnSpan(sep, 4);
                    gridPane.add(sep, 1, row);
                    row++;
                    continue;
                }
                if (pref.getKey().equals(PreferencesManager.INFO_KEY)) {
                    row++;
                    Label label = new Label(pref.getLabel());
                    label.setStyle("-fx-font-size:16");
                    label.setStyle("-fx-font-weight: bold");
                    GridPane.setColumnSpan(label, 4);
                    gridPane.add(label, 1, row);
                    row += 2;
                    continue;
                }
                if (pref.group != null && !pref.group.equals(currentGroup)) {
                    // Start a new group
                    row = 0;
                    currentGroup = pref.group;
                    gridPane = new GridPane();
                    gridPane.setHgap(5);
                    gridPane.setVgap(5);
                    vBox.getChildren().add(gridPane);
                    TitledPane tp = new TitledPane(currentGroup, gridPane);
                    tp.setCollapsible(false);
                    vBox.getChildren().add(tp);
                    vBox.setMargin(tp, new Insets(10, 0, 0, 0));
                }
                if (pref.getType().equals("boolean")) {
                    CheckBox cb = new CheckBox(pref.getLabel());
                    cb.setSelected(preferences.getAsBoolean(pref.getKey()));
                    cb.setOnAction( event -> {
                        updatedPrefs.put(pref.getKey(), Boolean.toString(cb.isSelected()));
                        System.out.println("Set " + pref.getLabel() + ": " + cb.isSelected());
                    });
                    GridPane.setColumnSpan(cb, 2);
                    gridPane.add(cb, 1, row);
                    if (tooltip != null) {
                        cb.setTooltip(tooltip);
                    }
                } else if (pref.getType().startsWith("select")) {
                    Label label = new Label(pref.getLabel());
                    String[] selections = Globals.whitespacePattern.split(pref.getType())[1].split("\\|");
                    final ComboBox comboBox = new ComboBox(FXCollections.observableArrayList(Arrays.asList(selections)));
                    comboBox.valueProperty().setValue(pref.getDefaultValue());
                    comboBox.valueProperty().addListener(( ov,  t,  t1) -> {
                        System.out.println("Set " + pref.getLabel() + " " + comboBox.valueProperty().toString());
                    });
                    gridPane.add(label, 1, row);
                    GridPane.setColumnSpan(comboBox, 3);
                    gridPane.add(comboBox, 2, row);
                    if (tooltip != null) {
                        label.setTooltip(tooltip);
                        comboBox.setTooltip(tooltip);
                    }
                } else {
                    Label label = new Label(pref.getLabel());
                    TextField field = new TextField(preferences.get(pref.getKey()));
                    field.setPrefWidth(500);
                    field.setOnAction( event -> {
                        final String text = field.getText();
                        if (validate(text, pref.getType())) {
                            updatedPrefs.put(pref.getKey(), text);
                        } else {
                            field.setText(preferences.get(pref.getKey()));
                        }
                    });
                    field.focusedProperty().addListener(( observable,  oldValue,  newValue) -> {
                        if (newValue == false) {
                            final String text = field.getText();
                            if (validate(text, pref.getType())) {
                                updatedPrefs.put(pref.getKey(), text);
                            } else {
                                field.setText(preferences.get(pref.getKey()));
                            }
                        }
                    });
                    gridPane.add(label, 1, row);
                    gridPane.add(field, 2, row);
                    if (tooltip != null) {
                        label.setTooltip(tooltip);
                        field.setTooltip(tooltip);
                    }
                }
                row++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (tabLabel.equalsIgnoreCase("Advanced")) {
            // Add IGV directory management at the end.  This is a special case
            String currentDirectory = DirectoryManager.getIgvDirectory().getAbsolutePath();
            final Label currentDirectoryLabel = new Label("IGV Directory: " + currentDirectory);
            final Button moveButton = new Button("Move...");
            row++;
            gridPane.add(currentDirectoryLabel, 1, row);
            GridPane.setHalignment(moveButton, HPos.RIGHT);
            gridPane.add(moveButton, 2, row);
            moveButton.setOnAction( event -> {
                UIUtilities.invokeOnEventThread(() -> {
                    final File igvDirectory = DirectoryManager.getIgvDirectory();
                    final File newDirectory = FileDialogUtils.chooseDirectory("Select IGV directory", DirectoryManager.getUserDirectory());
                    if (newDirectory != null && !newDirectory.equals(igvDirectory)) {
                        DirectoryManager.moveIGVDirectory(newDirectory);
                        Platform.runLater(() -> currentDirectoryLabel.setText(newDirectory.getAbsolutePath()));
                    }
                });
            });
        }
    }
    HBox hbox = new HBox();
    hbox.setAlignment(Pos.CENTER_RIGHT);
    hbox.setPadding(new Insets(15, 12, 15, 12));
    hbox.setSpacing(5);
    hbox.setStyle("-fx-background-color: #336699;");
    Button cancelBUtton = new Button("Cancel");
    cancelBUtton.setPrefSize(100, 20);
    cancelBUtton.setOnAction(( event) -> {
        SwingUtilities.invokeLater(() -> parent.setVisible(false));
    });
    Button saveButton = new Button("Save");
    saveButton.setPrefSize(100, 20);
    saveButton.setDefaultButton(true);
    saveButton.setOnAction(( event) -> {
        PreferencesManager.updateAll(updatedPreferencesMap);
        SwingUtilities.invokeLater(() -> parent.setVisible(false));
        if (IGV.hasInstance()) {
            IGV.getInstance().doRefresh();
        }
    });
    hbox.getChildren().addAll(cancelBUtton, saveButton);
    borderPane.setBottom(hbox);
    fxPanel.setScene(scene);
}
Example 93
Project: jace-master  File: ConfigurationUIController.java View source code
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 (NoSuchFieldExceptionSecurityException | IllegalArgumentException | IllegalAccessException |  ex) {
        Logger.getLogger(ConfigurationUIController.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
Example 94
Project: jdime-master  File: State.java View source code
/**
     * Returns a <code>State</code> with (where possible) the values initialized to the defaults specified using the
     * {@link JDimeConfig}.
     *
     * @return the default <code>State</code>
     */
public static State defaultState() {
    State state = new State();
    state.treeViewTabs = new ArrayList<>();
    state.output = FXCollections.observableArrayList();
    state.left = config.get(DEFAULT_LEFT).orElse("");
    state.base = config.get(DEFAULT_BASE).orElse("");
    state.right = config.get(DEFAULT_RIGHT).orElse("");
    state.jDime = config.get(DEFAULT_JDIME_EXEC).orElse("");
    state.cmdArgs = config.get(DEFAULT_ARGS).orElse("");
    state.debugMode = false;
    return state;
}
Example 95
Project: jfxvnc-master  File: ConnectViewPresenter.java View source code
@Override
public void initialize(URL location, ResourceBundle resources) {
    ProtocolConfiguration prop = con.getConfiguration();
    historyList.setItems(ctx.getHistory());
    clearBtn.setOnAction( a -> historyList.getItems().clear());
    securityCombo.getItems().addAll(FXCollections.observableArrayList(SecurityType.NONE, SecurityType.VNC_Auth));
    securityCombo.getSelectionModel().selectedItemProperty().addListener(( l,  a,  b) -> {
        prop.securityProperty().set(b != null ? b : SecurityType.UNKNOWN);
    });
    pwdField.disableProperty().bind(Bindings.equal(SecurityType.NONE, securityCombo.getSelectionModel().selectedItemProperty()));
    prop.hostProperty().bindBidirectional(ipField.textProperty());
    StringConverter<Number> converter = new NumberStringConverter("#");
    Bindings.bindBidirectional(portField.textProperty(), prop.portProperty(), converter);
    prop.passwordProperty().bindBidirectional(pwdField.textProperty());
    prop.sslProperty().bindBidirectional(sslCB.selectedProperty());
    prop.sharedProperty().bindBidirectional(sharedCB.selectedProperty());
    forceRfb33CB.setSelected(prop.versionProperty().get() == ProtocolVersion.RFB_3_3);
    forceRfb33CB.selectedProperty().addListener(( l,  a,  b) -> prop.versionProperty().set(b ? ProtocolVersion.RFB_3_3 : ProtocolVersion.RFB_3_8));
    listeningCB.selectedProperty().bindBidirectional(con.listeningModeProperty());
    Bindings.bindBidirectional(listeningPortField.textProperty(), con.listeningPortProperty(), converter);
    listeningPortField.disableProperty().bind(listeningCB.selectedProperty().not());
    prop.rawEncProperty().bindBidirectional(rawCB.selectedProperty());
    prop.copyRectEncProperty().bindBidirectional(copyrectCB.selectedProperty());
    prop.hextileEncProperty().bindBidirectional(hextileCB.selectedProperty());
    prop.clientCursorProperty().bindBidirectional(cursorCB.selectedProperty());
    prop.desktopSizeProperty().bindBidirectional(desktopCB.selectedProperty());
    prop.zlibEncProperty().bindBidirectional(zlibCB.selectedProperty());
    portField.textProperty().addListener(( observable,  oldValue,  newValue) -> {
        if (newValue != null && !newValue.isEmpty() && !newValue.matches("[0-9]+")) {
            if (!oldValue.matches("[0-9]+")) {
                ((StringProperty) observable).setValue("");
                return;
            }
            ((StringProperty) observable).setValue(oldValue);
        }
    });
    con.connectingProperty().addListener(( l,  a,  b) -> Platform.runLater(() -> ipField.getParent().setDisable(b)));
    ctx.bind(ipField.textProperty(), "hostField");
    ctx.bind(portField.textProperty(), "portField");
    ctx.bind(userField.textProperty(), "userField");
    ctx.bind(pwdField.textProperty(), "pwdField");
    ctx.bind(securityCombo, "authType");
    ctx.bind(sslCB.selectedProperty(), "useSSL");
    ctx.bind(sharedCB.selectedProperty(), "useSharedView");
    ctx.bind(forceRfb33CB.selectedProperty(), "forceRfb33");
    ctx.bind(listeningCB.selectedProperty(), "listeningMode");
    ctx.bind(listeningPortField.textProperty(), "listeningPortField");
    ctx.bind(rawCB.selectedProperty(), "useRaw");
    ctx.bind(copyrectCB.selectedProperty(), "useCopyRect");
    ctx.bind(hextileCB.selectedProperty(), "useHextile");
    ctx.bind(cursorCB.selectedProperty(), "useCursor");
    ctx.bind(desktopCB.selectedProperty(), "useDesktopSize");
    ctx.bind(zlibCB.selectedProperty(), "useZlib");
    if (securityCombo.getSelectionModel().getSelectedIndex() < 0) {
        securityCombo.getSelectionModel().select(SecurityType.VNC_Auth);
    }
    historyList.getSelectionModel().selectedItemProperty().addListener(( l,  a,  b) -> updateData(b));
    con.connectInfoProperty().addListener(( l,  a,  b) -> Platform.runLater(() -> addToHistory(b)));
}
Example 96
Project: JXTN-master  File: FXCanvas2.java View source code
private void sendInputMethodEventToFX() {
    String text = this.getTextForEvent(this.ime.getText());
    EmbeddedSceneInterface scenePeer = this.getScenePeer();
    if (scenePeer != null) {
        String committed = text.substring(0, this.ime.getCommitCount());
        if (this.ime.getText().length() == this.ime.getCommitCount()) {
            // Send empty text when committed, because the actual chars will then be immediately sent via keys.
            scenePeer.inputMethodEvent(javafx.scene.input.InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, FXCollections.emptyObservableList(), "", this.ime.getCompositionOffset());
        } else {
            ObservableList<InputMethodTextRun> composed = this.inputMethodEventComposed(text, this.ime.getCommitCount());
            scenePeer.inputMethodEvent(javafx.scene.input.InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, composed, committed, this.ime.getCaretOffset());
            this.updateImeCandicatePos();
        }
    }
}
Example 97
Project: KoreanDictionary-master  File: KoreanDictionary.java View source code
@Override
public void start(Stage stage) throws Exception {
    //Init window
    stage.setMinWidth(250);
    stage.setMinHeight(500);
    stage.setWidth(400);
    stage.setHeight(600);
    stage.setTitle("KoreanDictionary");
    stage.setOnCloseRequest( value -> System.exit(0));
    //Create nodes
    EventHandler<ActionEvent> searchHandler =  value -> this.search();
    input = new TextField();
    input.setOnAction(searchHandler);
    input.setPromptText("검색어를 입력하세요");
    HBox.setHgrow(input, Priority.ALWAYS);
    Button searchButton = new Button("검색");
    searchButton.setOnAction(searchHandler);
    filterNonUniversalWords = new CheckBox("방언, �한어, 옛� 제외");
    filterNonUniversalWords.setSelected(true);
    ToggleGroup group = new ToggleGroup();
    startsWith = new RadioButton("시작 문�");
    RadioButton endsWith = new RadioButton("ë?? 문ìž?");
    startsWith.setToggleGroup(group);
    endsWith.setToggleGroup(group);
    startsWith.setSelected(true);
    list = new ListView<>();
    list.setOnMouseClicked( click -> {
        if (click.getClickCount() == 2) {
            KoreanDictionary.copyToClipboard(list.getSelectionModel().getSelectedItem());
        }
    });
    list.setItems(FXCollections.observableArrayList("간단한 한국어 사전", "- 국립국어� 표준국어대사전� 사용했습니다", "", "Copyright (c) 2015 ChalkPE", "Licensed under GNU General Public License v3.0", "", "https://github.com/ChalkPE/KoreanDictionary"));
    progress = new ProgressIndicator();
    StackPane.setMargin(progress, new Insets(50));
    //Init layouts
    BorderPane optionPane = new BorderPane();
    optionPane.setLeft(filterNonUniversalWords);
    optionPane.setRight(new HBox(6, startsWith, endsWith));
    VBox top = new VBox(6, new HBox(6, input, searchButton), optionPane);
    top.setPadding(new Insets(6));
    contents = new StackPane(list);
    BorderPane root = new BorderPane();
    root.setTop(top);
    root.setCenter(contents);
    Scene scene = new Scene(new Group());
    scene.setRoot(root);
    stage.setScene(scene);
    stage.show();
}
Example 98
Project: LibFX-master  File: ControlPropertyListenerDemo.java View source code
// #end CONSTRUCTION & MAIN
// #begin DEMOS
/**
	 * Demonstrates the simple case, in which a value processor is added for some key.
	 */
private void simpleCase() {
    ObservableMap<Object, Object> properties = FXCollections.observableHashMap();
    // build and attach the listener
    ControlProperties.<String>on(properties).forKey("Key").processValue( value -> System.out.println(" -> " + value)).buildAttached();
    // set values of the correct type for the correct key
    System.out.print("Set \"Value\" for the correct key for the first time: ");
    properties.put("Key", "Value");
    System.out.print("Set \"Value\" for the correct key for the second time: ");
    properties.put("Key", "Value");
    // set values of the wrong type:
    System.out.println("Set an Integer for the correct key: ... (nothing will happen)");
    properties.put("Key", 5);
    // set values for the wrong key
    System.out.println("Set \"Value\" for another key: ... (nothing will happen)");
    properties.put("OtherKey", "Value");
    System.out.println();
}
Example 99
Project: mqtt-spy-master  File: EditConnectionSubscriptionsController.java View source code
// ===============================
// === Initialisation ============
// ===============================
public void initialize(URL location, ResourceBundle resources) {
    // Subscriptions
    searchScriptsText.textProperty().addListener(basicOnChangeListener);
    createTabSubscriptionColumn.setCellValueFactory(new PropertyValueFactory<SubscriptionTopicProperties, Boolean>("show"));
    createTabSubscriptionColumn.setCellFactory(new Callback<TableColumn<SubscriptionTopicProperties, Boolean>, TableCell<SubscriptionTopicProperties, Boolean>>() {

        public TableCell<SubscriptionTopicProperties, Boolean> call(TableColumn<SubscriptionTopicProperties, Boolean> p) {
            final TableCell<SubscriptionTopicProperties, Boolean> cell = new TableCell<SubscriptionTopicProperties, Boolean>() {

                @Override
                public void updateItem(final Boolean item, boolean empty) {
                    super.updateItem(item, empty);
                    if (!isEmpty()) {
                        final SubscriptionTopicProperties shownItem = getTableView().getItems().get(getIndex());
                        CheckBox box = new CheckBox();
                        box.selectedProperty().bindBidirectional(shownItem.showProperty());
                        box.setOnAction(new EventHandler<ActionEvent>() {

                            @Override
                            public void handle(ActionEvent event) {
                                logger.info("New value = {} {}", shownItem.topicProperty().getValue(), shownItem.showProperty().getValue());
                                onChange();
                            }
                        });
                        setGraphic(box);
                    } else {
                        setGraphic(null);
                    }
                }
            };
            cell.setAlignment(Pos.CENTER);
            return cell;
        }
    });
    subscriptionTopicColumn.setCellValueFactory(new PropertyValueFactory<SubscriptionTopicProperties, String>("topic"));
    subscriptionTopicColumn.setCellFactory(TextFieldTableCell.<SubscriptionTopicProperties>forTableColumn());
    subscriptionTopicColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<SubscriptionTopicProperties, String>>() {

        @Override
        public void handle(CellEditEvent<SubscriptionTopicProperties, String> event) {
            BaseTopicProperty p = event.getRowValue();
            String newValue = event.getNewValue();
            p.topicProperty().set(newValue);
            logger.debug("New value = {}", subscriptionsTable.getSelectionModel().getSelectedItem().topicProperty().getValue());
            onChange();
        }
    });
    scriptColumn.setCellValueFactory(new PropertyValueFactory<SubscriptionTopicProperties, String>("script"));
    scriptColumn.setCellFactory(TextFieldTableCell.<SubscriptionTopicProperties>forTableColumn());
    scriptColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<SubscriptionTopicProperties, String>>() {

        @Override
        public void handle(CellEditEvent<SubscriptionTopicProperties, String> event) {
            SubscriptionTopicProperties p = event.getRowValue();
            String newValue = event.getNewValue();
            p.scriptProperty().set(newValue);
            logger.debug("New value = {}", subscriptionsTable.getSelectionModel().getSelectedItem().scriptProperty().getValue());
            onChange();
        }
    });
    final ObservableList<Integer> qosChoice = FXCollections.observableArrayList(new Integer(0), new Integer(1), new Integer(2));
    qosSubscriptionColumn.setCellValueFactory(new PropertyValueFactory<SubscriptionTopicProperties, Integer>("qos"));
    qosSubscriptionColumn.setCellFactory(new Callback<TableColumn<SubscriptionTopicProperties, Integer>, TableCell<SubscriptionTopicProperties, Integer>>() {

        public TableCell<SubscriptionTopicProperties, Integer> call(TableColumn<SubscriptionTopicProperties, Integer> p) {
            final TableCell<SubscriptionTopicProperties, Integer> cell = new TableCell<SubscriptionTopicProperties, Integer>() {

                @Override
                public void updateItem(final Integer item, boolean empty) {
                    super.updateItem(item, empty);
                    if (!isEmpty()) {
                        final SubscriptionTopicProperties shownItem = getTableView().getItems().get(getIndex());
                        ChoiceBox box = new ChoiceBox();
                        box.setItems(qosChoice);
                        box.setId("subscriptionQosChoice");
                        int qos = shownItem.qosProperty().getValue();
                        box.getSelectionModel().select(qos);
                        box.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Integer>() {

                            @Override
                            public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
                                shownItem.qosProperty().setValue(newValue);
                                logger.info("New value = {} {}", shownItem.topicProperty().getValue(), shownItem.qosProperty().getValue());
                                onChange();
                            }
                        });
                        setGraphic(box);
                    } else {
                        setGraphic(null);
                    }
                }
            };
            cell.setAlignment(Pos.CENTER);
            return cell;
        }
    });
    qosSubscriptionColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<SubscriptionTopicProperties, Integer>>() {

        @Override
        public void handle(CellEditEvent<SubscriptionTopicProperties, Integer> event) {
            SubscriptionTopicProperties p = event.getRowValue();
            Integer newValue = event.getNewValue();
            p.qosProperty().set(newValue);
            logger.debug("New value = {}", subscriptionsTable.getSelectionModel().getSelectedItem().qosProperty().getValue());
            onChange();
        }
    });
}
Example 100
Project: OG-Commons-master  File: ScheduleGui.java View source code
//-------------------------------------------------------------------------
@Override
public void start(Stage primaryStage) {
    // setup GUI elements
    Label startLbl = new Label("Start date:");
    DatePicker startInp = new DatePicker(LocalDate.now());
    startLbl.setLabelFor(startInp);
    startInp.setShowWeekNumbers(false);
    Label endLbl = new Label("End date:");
    DatePicker endInp = new DatePicker(LocalDate.now().plusYears(1));
    endLbl.setLabelFor(endInp);
    endInp.setShowWeekNumbers(false);
    Label freqLbl = new Label("Frequency:");
    ChoiceBox<Frequency> freqInp = new ChoiceBox<>(FXCollections.observableArrayList(Frequency.P1M, Frequency.P2M, Frequency.P3M, Frequency.P4M, Frequency.P6M, Frequency.P12M));
    freqLbl.setLabelFor(freqInp);
    freqInp.setValue(Frequency.P3M);
    Label stubLbl = new Label("Stub:");
    ObservableList<StubConvention> stubOptions = FXCollections.observableArrayList(StubConvention.values());
    stubOptions.add(0, null);
    ChoiceBox<StubConvention> stubInp = new ChoiceBox<>(stubOptions);
    stubLbl.setLabelFor(stubInp);
    stubInp.setValue(StubConvention.SHORT_INITIAL);
    Label rollLbl = new Label("Roll:");
    ChoiceBox<RollConvention> rollInp = new ChoiceBox<>(FXCollections.observableArrayList(null, RollConventions.NONE, RollConventions.EOM, RollConventions.IMM, RollConventions.IMMAUD, RollConventions.IMMNZD, RollConventions.SFE));
    rollLbl.setLabelFor(rollInp);
    rollInp.setValue(RollConventions.NONE);
    Label bdcLbl = new Label("Adjust:");
    ChoiceBox<BusinessDayConvention> bdcInp = new ChoiceBox<>(FXCollections.observableArrayList(BusinessDayConventions.NO_ADJUST, BusinessDayConventions.FOLLOWING, BusinessDayConventions.MODIFIED_FOLLOWING, BusinessDayConventions.PRECEDING, BusinessDayConventions.MODIFIED_PRECEDING, BusinessDayConventions.MODIFIED_FOLLOWING_BI_MONTHLY, BusinessDayConventions.NEAREST));
    bdcLbl.setLabelFor(bdcInp);
    bdcInp.setValue(BusinessDayConventions.MODIFIED_FOLLOWING);
    Label holidayLbl = new Label("Holidays:");
    ChoiceBox<HolidayCalendar> holidayInp = new ChoiceBox<>(FXCollections.observableArrayList(HolidayCalendars.CHZU, HolidayCalendars.GBLO, HolidayCalendars.EUTA, HolidayCalendars.FRPA, HolidayCalendars.USGS));
    holidayLbl.setLabelFor(holidayInp);
    holidayInp.setValue(HolidayCalendars.GBLO);
    TableView<SchedulePeriod> resultGrid = new TableView<>();
    TableColumn<SchedulePeriod, LocalDate> unadjustedCol = new TableColumn<>("Unadjusted dates");
    TableColumn<SchedulePeriod, LocalDate> adjustedCol = new TableColumn<>("Adjusted dates");
    TableColumn<SchedulePeriod, LocalDate> resultUnadjStartCol = new TableColumn<>("Start");
    resultUnadjStartCol.setCellValueFactory(new TableCallback<>(SchedulePeriod.meta().unadjustedStartDate()));
    TableColumn<SchedulePeriod, LocalDate> resultUnadjEndCol = new TableColumn<>("End");
    resultUnadjEndCol.setCellValueFactory(new TableCallback<>(SchedulePeriod.meta().unadjustedEndDate()));
    TableColumn<SchedulePeriod, LocalDate> resultStartCol = new TableColumn<>("Start");
    resultStartCol.setCellValueFactory(new TableCallback<>(SchedulePeriod.meta().startDate()));
    TableColumn<SchedulePeriod, LocalDate> resultEndCol = new TableColumn<>("End");
    resultEndCol.setCellValueFactory(new TableCallback<>(SchedulePeriod.meta().endDate()));
    unadjustedCol.getColumns().add(resultUnadjStartCol);
    unadjustedCol.getColumns().add(resultUnadjEndCol);
    adjustedCol.getColumns().add(resultStartCol);
    adjustedCol.getColumns().add(resultEndCol);
    resultGrid.getColumns().add(unadjustedCol);
    resultGrid.getColumns().add(adjustedCol);
    resultGrid.setPlaceholder(new Label("Schedule not yet generated"));
    unadjustedCol.prefWidthProperty().bind(resultGrid.widthProperty().divide(2));
    adjustedCol.prefWidthProperty().bind(resultGrid.widthProperty().divide(2));
    resultUnadjStartCol.prefWidthProperty().bind(unadjustedCol.widthProperty().divide(2));
    resultUnadjEndCol.prefWidthProperty().bind(unadjustedCol.widthProperty().divide(2));
    resultStartCol.prefWidthProperty().bind(adjustedCol.widthProperty().divide(2));
    resultEndCol.prefWidthProperty().bind(adjustedCol.widthProperty().divide(2));
    // setup generation button
    // this uses the GUI thread which is not the best idea
    Button btn = new Button();
    btn.setText("Generate");
    btn.setOnAction( event -> {
        LocalDate start = startInp.getValue();
        LocalDate end = endInp.getValue();
        Frequency freq = freqInp.getValue();
        StubConvention stub = stubInp.getValue();
        RollConvention roll = rollInp.getValue();
        HolidayCalendar holCal = holidayInp.getValue();
        BusinessDayConvention bdc = bdcInp.getValue();
        BusinessDayAdjustment bda = BusinessDayAdjustment.of(bdc, holCal);
        PeriodicSchedule defn = PeriodicSchedule.builder().startDate(start).endDate(end).frequency(freq).businessDayAdjustment(bda).stubConvention(stub).rollConvention(roll).build();
        try {
            Schedule schedule = defn.createSchedule();
            System.out.println(schedule);
            resultGrid.setItems(FXCollections.observableArrayList(schedule.getPeriods()));
        } catch (ScheduleException ex) {
            resultGrid.setItems(FXCollections.emptyObservableList());
            resultGrid.setPlaceholder(new Label(ex.getMessage()));
            System.out.println(ex.getMessage());
        }
    });
    // layout the components
    GridPane gp = new GridPane();
    gp.setHgap(10);
    gp.setVgap(10);
    gp.setPadding(new Insets(0, 10, 0, 10));
    gp.add(startLbl, 1, 1);
    gp.add(startInp, 2, 1);
    gp.add(endLbl, 1, 2);
    gp.add(endInp, 2, 2);
    gp.add(freqLbl, 1, 3);
    gp.add(freqInp, 2, 3);
    gp.add(bdcLbl, 3, 1);
    gp.add(bdcInp, 4, 1);
    gp.add(holidayLbl, 3, 2);
    gp.add(holidayInp, 4, 2);
    gp.add(stubLbl, 3, 3);
    gp.add(stubInp, 4, 3);
    gp.add(rollLbl, 3, 4);
    gp.add(rollInp, 4, 4);
    gp.add(btn, 3, 5, 2, 1);
    gp.add(resultGrid, 1, 7, 4, 1);
    BorderPane bp = new BorderPane(gp);
    Scene scene = new Scene(bp, 600, 600);
    // launch
    primaryStage.setTitle("Periodic schedule generator");
    primaryStage.setScene(scene);
    primaryStage.show();
}
Example 101
Project: Projectiler-master  File: ProjectilerController.java View source code
@Override
public void handle(final WorkerStateEvent t) {
    projectChooser.getItems().clear();
    projectChooser.getItems().addAll(FXCollections.observableArrayList(projectilerTask.valueProperty().get()));
    projectChooser.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(final ObservableValue<? extends String> arg0, final String arg1, final String arg2) {
            if (arg2 != null && !arg2.isEmpty()) {
                projectiler.saveProjectName(arg2);
            }
        }
    });
    final String projectName = UserDataStore.getInstance().getProjectName();
    if (projectName == null) {
        projectChooser.getSelectionModel().select(0);
    } else {
        projectChooser.getSelectionModel().select(projectName);
    }
    UITools.fadeIn(projectChooser);
}