Exemplo n.º 1
0
 public Project() { // NO_UCD (unused code)
   super();
   expressions = new ArrayList<Expression>();
   triggers = new ArrayList<Trigger>();
   variables = FXCollections.observableList(new ArrayList<UserVariable>());
   surveys = FXCollections.observableList(new ArrayList<Survey>());
   uielements = FXCollections.observableList(new ArrayList<UIElement>());
   this.name = "My project";
   this.description = "A brand spanking new project";
 }
Exemplo n.º 2
0
  @Inject
  public FileDetailsCtrl(FileNavigationState navState) {
    this.navState = navState;
    this.navState.selectedFileProperty().addListener(new SelectedFileListener());

    listFiles = FXCollections.observableList(new ArrayList<>());
    fileDetails = FXCollections.observableList(new ArrayList<>());

    fileGrid.setCellHeight(80);
    fileGrid.setCellWidth(100);

    fileGrid.getItems().addAll(listFiles);
    fileDetailsList.getItems().addAll(fileDetails);
  }
Exemplo n.º 3
0
  public SQLHistorySearchCtrl(
      SQLTextAreaServices sqlTextAreaServices,
      Session session,
      ObservableList<SQLHistoryEntry> items) {
    _sqlTextAreaServices = sqlTextAreaServices;

    FxmlHelper<SQLHistorySearchView> fxmlHelper = new FxmlHelper<>(SQLHistorySearchView.class);
    _view = fxmlHelper.getView();

    _dialog = new Stage();
    _dialog.setTitle(
        new I18n(getClass())
            .t("SQLHistorySearchCtrl.title", session.getMainTabContext().getSessionTabTitle()));
    _dialog.initModality(Modality.WINDOW_MODAL);
    _dialog.initOwner(AppState.get().getPrimaryStage());
    Region region = fxmlHelper.getRegion();
    _dialog.setScene(new Scene(region));

    GuiUtils.makeEscapeClosable(region);

    new StageDimensionSaver(
        "sqlhistorysearch",
        _dialog,
        new Pref(getClass()),
        region.getPrefWidth(),
        region.getPrefHeight(),
        _dialog.getOwner());

    _view.cboFilterType.setItems(
        FXCollections.observableList(Arrays.asList(SqlHistoryFilterType.values())));
    _view.cboFilterType.getSelectionModel().selectFirst();

    _view.btnApply.setOnAction(e -> onApply());
    _view.chkFiltered.setOnAction(e -> onChkFiltered());

    _view.split.getItems().add(_tblHistory);
    _view.split.getItems().add(_txtSqlPreview);

    _originalTableLoader = new RowObjectTableLoader<>();
    _originalTableLoader.initColsByAnnotations(SQLHistoryEntry.class);
    _originalTableLoader.addRowObjects(items);
    _currentLoader = _originalTableLoader.cloneLoader();
    _currentLoader.load(_tblHistory);

    _tblHistory
        .getSelectionModel()
        .selectedItemProperty()
        .addListener((observable, oldValue, newValue) -> onTableSelectionChanged());

    _tblHistory.setOnMouseClicked(e -> onTblHistoryClicked(e));

    _txtSqlPreview.setEditable(false);

    _dialog.setOnCloseRequest(e -> close());

    _view.txtFilter.requestFocus();

    _splitPositionSaver.apply(_view.split);
    _dialog.showAndWait();
  }
Exemplo n.º 4
0
  @Override
  public void start(Stage primaryStage) {

    primaryStage.setTitle("http://java-buddy.blogspot.com/");

    prepareMyList();
    ListView<MyObject> listView = new ListView<MyObject>();
    ObservableList<MyObject> myObservableList = FXCollections.observableList(myList);
    listView.setItems(myObservableList);

    listView.setCellFactory(
        new Callback<ListView<MyObject>, ListCell<MyObject>>() {
          @Override
          public ListCell<MyObject> call(ListView<MyObject> p) {

            ListCell<MyObject> cell =
                new ListCell<MyObject>() {
                  @Override
                  protected void updateItem(MyObject t, boolean bln) {
                    super.updateItem(t, bln);
                    if (t != null) {
                      setText(t.getDay() + ":" + t.getNumber());
                    }
                  }
                };

            return cell;
          }
        });

    StackPane root = new StackPane();
    root.getChildren().add(listView);
    primaryStage.setScene(new Scene(root, 300, 250));
    primaryStage.show();
  }
  public Stack(final Stack<T> otherStack) {
    if (otherStack == null) {
      throw new IllegalArgumentException("Cannot create stack from stack: argument is null.");
    }

    elementsProperty.set(FXCollections.observableList(otherStack.toList()));
  }
  public Stack(final List<T> list) {
    if (list == null) {
      throw new IllegalArgumentException("Cannot create stack from list: argument is null.");
    }

    elementsProperty.set(FXCollections.observableList(list));
  }
 public void fillStaffTableWithVO(InstitutionVO vo) {
   institutionID = vo.getInstitutionID();
   if (vo != null) {
     initLabel(vo);
     List<StaffVO> staffVOs = manageblStaffService.getStaffByInstitution(vo.getInstitutionID());
     this.staff_TableView.setItems(FXCollections.observableList(staffVOs));
   } else {
     System.err.println("wrong in fillStaffTableWithVO : input vo is null");
   }
 }
Exemplo n.º 8
0
 private void refresh() {
   List<ImageResource> imageResources = new ArrayList<>();
   List<Resource> resources =
       book.getResources()
           .getResourcesByMediaTypes(
               new MediaType[] {MediaType.GIF, MediaType.PNG, MediaType.SVG, MediaType.JPG});
   for (Resource resource : resources) {
     imageResources.add((ImageResource) resource);
   }
   tableView.setItems(FXCollections.observableList(imageResources));
   tableView.getSelectionModel().select(0);
 }
  @Override
  public ObservableList<PlayerAchievement> getPlayerAchievements(String username) {
    if (userService.getUsername().equals(username)) {
      if (readOnlyPlayerAchievements.isEmpty()) {
        updatePlayerAchievementsFromServer();
      }
      return readOnlyPlayerAchievements;
    }

    int playerId = playerService.getPlayerForUsername(username).getId();
    return FXCollections.observableList(fafApiAccessor.getPlayerAchievements(playerId));
  }
Exemplo n.º 10
0
  public CharacterController() {

    setCharacterService(new CharacterServiceImpl());

    List<Character> characters = getCharacterService().CharacterList();

    if (characters != null && !characters.isEmpty()) {
      ObservableList<Character> list = FXCollections.observableList(characters);
      setCharacterList(list);
    } else {
      System.out.println("Database table doesn't have any character data");
    }
  }
  private ObservableList<Protocol> getProtocolList() {
    ArrayList<Protocol> list = new ArrayList<Protocol>();
    list.add(Protocol.ACTIVE_MQ);
    list.add(Protocol.RABBIT_MQ);
    list.add(Protocol.STREAM_SERVICE);
    list.add(Protocol.TCP);
    list.add(Protocol.TCP_SERVER);
    list.add(Protocol.WEBSOCKETS);
    list.add(Protocol.WEBSOCKET_SERVER);
    list.add(Protocol.KAFKA);

    return FXCollections.observableList(list);
  }
Exemplo n.º 12
0
 /**
  * Incorrect test assumption: updates to the items don't change the indices, no event to fire from
  * the indices. They are immutable, anyway.
  *
  * <p>The assumption had some meaning as long as IndexMappedList didn't get the real change from
  * the backing list - now it doesn't and can fire on its own as needed.
  *
  * @see IndexMappedListTest#testItemsUpdate()
  */
 @Test
 @Ignore
 public void testItemsUpdate() {
   ObservableList<Person> base = Person.persons();
   ObservableList<Person> persons =
       FXCollections.observableList(base, p -> new Observable[] {p.firstNameProperty()});
   IndicesBase<Person> indicesList = new IndicesList<>(persons);
   int[] indices = new int[] {1, 3, 5};
   indicesList.addIndices(indices);
   ListChangeReport report = new ListChangeReport(indicesList);
   //        new PrintingListChangeListener("Set item at 3", indicesList);
   persons.get(3).setFirstName("newName");
   assertEquals(1, report.getEventCount());
 }
  @Override
  public void atualizarLista() {
    try {
      String text = pesquisa.getText();

      tabela.getItems().clear();
      observavel = f.buscarFuncionarioPorNomeQueInicia(text);
      configurarColunaEditar();

      tabela.setItems(FXCollections.observableList(observavel));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 14
0
 public void fillStaffTable(String institutionID) {
   InstitutionVO vo = null;
   if (institutionID.charAt(3) == '0') {
     vo = manageblCenterService.searchCenter(institutionID);
   } else { // not in center
     vo = manageblHallService.searchHall(institution_Field.getText());
   }
   if (vo == null) { // neither in center nor in hall
     informController.informWrong("请输入正确的机构编号");
     return;
   } else {
     this.institutionID = vo.getInstitutionID();
     initLabel(vo);
     List<StaffVO> staffVOs = manageblStaffService.getStaffByInstitution(vo.getInstitutionID());
     this.staff_TableView.setItems(FXCollections.observableList(staffVOs));
   }
 }
Exemplo n.º 15
0
 private void setFormData() {
   if (oldItem != null) {
     btnOk.setDisable(true);
     long ldate = oldItem.getTransDate().getTime();
     Date d2 = new Date(ldate);
     LocalDate localDate = d2.toLocalDate();
     transDate.setValue(localDate);
     transDescription.setText(oldItem.getTransDesc());
     transAmt.setText(Float.toString(oldItem.getTransAmt()));
     transBalance.setText(Float.toString(oldItem.getTransBal()));
     accountNum.setValue(oldItem.getAccountNum());
     transId.setText(oldItem.getId().toString());
     if (oldItem.getPrimaryCat() != null) {
       String str = oldItem.getPrimaryCat().getDescription();
       primaryCat.setValue(str);
     }
     if (oldItem.getPayment() != null) {
       paymentDetail.setList(FXCollections.observableList(oldItem.getPayment()));
       paymentDetail.setItems(paymentDetail.getList());
       Category c = oldItem.getSubCat();
       if (c != null) {
         subCat.setValue(c.getDescription());
       }
     }
     if (oldItem.getCheckNum() != null) {
       checkNum.setText(oldItem.getCheckNum());
     }
     transDate.setDisable(true);
     transId.setDisable(true);
     transAmt.setDisable(true);
     btnOk.setDisable(true);
   } else {
     Date date = new Date(newItem.getTransDate().getTime());
     transDate.setValue(date.toLocalDate());
     transAmt.setText(Float.toString(newItem.getTransAmt()));
     transDescription.setText(newItem.getTransDesc());
     accountNum.setValue(newItem.getAccountNum());
     transId.setText(newItem.getId().toString());
     primaryCat.setValue(newItem.getPrimaryCat().getDescription());
   }
 }
Exemplo n.º 16
0
public class BlockingExecutor {

  public final AbstractExecutorService tpe =
      new ForkJoinPool(Runtime.getRuntime().availableProcessors() - 1);
  public final BooleanBinding isIdleBinding;
  public final DoubleBinding overallProgressBinding;
  public final ObservableList<TimeTask<?>> scheduledTasks =
      FXCollections.observableList(Collections.synchronizedList(new LinkedList<TimeTask<?>>()));
  public final Property<TimeTask<?>> currentTaskProperty = new SimpleObjectProperty<TimeTask<?>>();

  private final Map<Dataset, DoubleBinding> datasetProgressBindings = new ConcurrentHashMap<>();

  public BlockingExecutor() {
    overallProgressBinding =
        Bindings.createDoubleBinding(
            () -> {
              if (scheduledTasks.isEmpty()) return 1d;
              double progress = 0d;
              for (TimeTask<?> task : scheduledTasks) {
                if (task.isDone()) progress += 1d;
                else if (task.getProgress() > 0) progress += task.getProgress();
              }
              return progress / (double) scheduledTasks.size();
            },
            scheduledTasks,
            currentTaskProperty);
    isIdleBinding =
        Bindings.createBooleanBinding(
            () -> overallProgressBinding.get() == 1d, overallProgressBinding);
    currentTaskProperty.addListener(
        (__, ___, task) -> {
          if (task.isDone()) next();
          else {
            task.exceptionProperty()
                .addListener(
                    (____, _____, exception) ->
                        new ErrorDialog(ConExpFX.instance.primaryStage, exception).showAndWait());
            task.setOnCancelled(____ -> next());
            task.setOnFailed(____ -> next());
            task.setOnSucceeded(____ -> next());
            tpe.submit(task);
          }
        });
  }

  public final void execute(final TimeTask<?> task) {
    Platform2.runOnFXThread(
        () -> {
          synchronized (scheduledTasks) {
            if (isIdleBinding.get()) currentTaskProperty.setValue(task);
            scheduledTasks.add(task);
            task.progressProperty()
                .addListener(
                    (__, ___, ____) -> {
                      overallProgressBinding.invalidate();
                      datasetProgressBindings.values().forEach(DoubleBinding::invalidate);
                    });
            task.stateProperty()
                .addListener(
                    (__, ___, ____) -> {
                      overallProgressBinding.invalidate();
                      datasetProgressBindings.values().forEach(DoubleBinding::invalidate);
                    });
          }
        });
  }

  private final void next() {
    synchronized (scheduledTasks) {
      if (!isIdleBinding.get())
        currentTaskProperty.setValue(
            scheduledTasks.get(scheduledTasks.indexOf(currentTaskProperty.getValue()) + 1));
    }
  }

  public final DoubleBinding datasetProgressBinding(final Dataset dataset) {
    if (datasetProgressBindings.containsKey(dataset)) return datasetProgressBindings.get(dataset);
    final DoubleBinding datasetProgressBinding =
        Bindings.createDoubleBinding(
            () -> {
              if (scheduledTasks.isEmpty()) return 1d;
              double progress = 0d;
              double tasks = 0d;
              for (TimeTask<?> task : scheduledTasks)
                if (task.getDataset() != null && task.getDataset().equals(dataset)) {
                  if (task.isDone()) progress += 1d;
                  else if (task.getProgress() > 0) progress += task.getProgress();
                  tasks++;
                }
              if (tasks > 0) return progress / tasks;
              return 1d;
            },
            scheduledTasks,
            currentTaskProperty);
    datasetProgressBindings.put(dataset, datasetProgressBinding);
    return datasetProgressBinding;
  }

  public final void cancel(final Dataset dataset) {
    scheduledTasks
        .filtered(task -> task.getDataset() != null && task.getDataset().equals(dataset))
        .forEach(task -> task.cancel());
    scheduledTasks.removeIf(task -> task.getDataset() != null && task.getDataset().equals(dataset));
    datasetProgressBindings.remove(dataset);
  }
}
/** Main application */
public class MainApplicationPresenter implements Initializable {

  public static final Logger LOGGER = LogManager.getLogger(MainApplicationPresenter.class);
  @FXML Label myoStatus;
  @FXML Label collectorStatus;
  @FXML Button startButton;
  @FXML Button stopButton;
  @FXML SimpleIndicator indicatorMyo;
  @FXML SimpleIndicator indicatorServer;
  @FXML ListView inboundConnections;
  @FXML OneEightyGauge gauge;
  List<String> connections = new ArrayList<>();
  ObservableList<String> observableList = FXCollections.observableList(connections);

  private boolean collecting = true;
  private Hub hub;
  private JsonDataCollector jsonDataCollector;

  @Override
  public void initialize(URL location, ResourceBundle resources) {
    indicatorMyo.setIndicatorStyle(SimpleIndicator.IndicatorStyle.RED);
    indicatorMyo.setOn(true);
    indicatorServer.setIndicatorStyle(SimpleIndicator.IndicatorStyle.GREEN);
    indicatorServer.setOn(true);
    statusUpdate("");
    stopButton.setDisable(true);
    startButton.setDisable(true);
    hub = new Hub(this.getClass().getCanonicalName());
    inboundConnections.setItems(observableList);
    LOGGER.info("Initialized");
  }

  private void statusUpdate(final String status) {
    myoStatus.setText(status);
  }

  public void startAction() {
    collecting = true;
    jsonDataCollector.getListeners().stream().forEach(RecordListener::start);
    startButton.setDefaultButton(false);
    stopButton.setDefaultButton(true);
    toggleButtons();
    // todo must be killed by stop action
    new Thread(
            () -> {
              while (collecting) {
                hub.run(100);
              }
              System.out.println("collecting = " + collecting);
            })
        .start();
  }

  public void stopAction() {
    collecting = false;
    jsonDataCollector.getListeners().stream().forEach(RecordListener::stop);
    toggleButtons();
    jsonDataCollector.getListeners().stream().forEach(s -> s.dump("Data"));
    startButton.setDefaultButton(true);
    stopButton.setDefaultButton(false);
  }

  private void toggleButtons() {
    startButton.setDisable(collecting);
    stopButton.setDisable(!collecting);
  }

  public void connectMyo() {
    try {

      LOGGER.info("Connecting to Myo");
      updateMyoStatus("Attempting to find a Myo...");
      Myo myo = hub.waitForMyo(10000);

      if (myo == null) {
        LOGGER.error("Unable to connect to Myo");
        throw new RuntimeException("Unable to find a Myo!");
      }

      myo.setStreamEmg(StreamEmgType.STREAM_EMG_ENABLED);
      LOGGER.info("EMG Stream enabled");
      updateMyoStatus("Connected to a Myo armband!");

      jsonDataCollector = new JsonDataCollector();
      jsonDataCollector.addListsner(new FileMyoDataCollector("c:\\tmp\\myo"));
      jsonDataCollector.addListsner(new SocketServerCollector());

      hub.addListener(jsonDataCollector);
      LOGGER.info("Listener added");

      indicatorMyo.setIndicatorStyle(SimpleIndicator.IndicatorStyle.GREEN);
      startButton.setDisable(false);
      startButton.setDefaultButton(true);

      Task<ObservableList<String>> task =
          new Task<ObservableList<String>>() {
            @Override
            protected ObservableList<String> call() throws Exception {

              while (true) {
                List<RecordListener> collect =
                    jsonDataCollector
                        .getListeners()
                        .stream()
                        .filter(s -> s instanceof SocketServerCollector)
                        .collect(Collectors.toList());
                List<String> connections =
                    collect
                        .stream()
                        .map(s -> ((SocketServerCollector) s).channels)
                        .flatMap(c -> c.stream().map(f -> mapRemoteAddress(f)))
                        .collect(Collectors.toList());
                updateValue(FXCollections.observableList(connections));
                Thread.sleep(10);
              }
            }
          };

      Task<Boolean> booleanTask =
          new Task<Boolean>() {
            @Override
            protected Boolean call() throws Exception {
              while (true) {
                List<RecordListener> collect =
                    jsonDataCollector
                        .getListeners()
                        .stream()
                        .filter(s -> s instanceof SocketServerCollector)
                        .collect(Collectors.toList());
                long count =
                    collect
                        .stream()
                        .map(s -> ((SocketServerCollector) s).channels)
                        .flatMap(Collection::stream)
                        .filter(AsynchronousSocketChannel::isOpen)
                        .count();
                updateValue(count > 0 ? Boolean.TRUE : Boolean.FALSE);
                Thread.sleep(10);
              }
            }
          };

      Task<SimpleIndicator.IndicatorStyle> stringTask =
          new Task<SimpleIndicator.IndicatorStyle>() {

            @Override
            protected SimpleIndicator.IndicatorStyle call() throws Exception {
              while (true) {
                List<RecordListener> collect =
                    jsonDataCollector
                        .getListeners()
                        .stream()
                        .filter(s -> s instanceof SocketServerCollector)
                        .collect(Collectors.toList());
                long count =
                    collect
                        .stream()
                        .map(s -> ((SocketServerCollector) s).channels)
                        .flatMap(Collection::stream)
                        .filter(AsynchronousSocketChannel::isOpen)
                        .count();

                updateValue(
                    count > 0
                        ? SimpleIndicator.IndicatorStyle.RED
                        : SimpleIndicator.IndicatorStyle.GREEN);
                Thread.sleep(10);
              }
            }
          };

      inboundConnections.itemsProperty().bind(task.valueProperty());
      indicatorServer.onProperty().bind(booleanTask.valueProperty());
      //            try {
      //                indicatorServer.indicatorStyleProperty().bind(stringTask.valueProperty());
      //            } catch (Throwable e) {
      //                //??Throws a null ppointer but it works??
      //            }

      Thread thread = new Thread(task);
      thread.setDaemon(true);
      thread.start();

      Thread thread2 = new Thread(booleanTask);
      thread2.setDaemon(true);
      thread2.start();

      Thread thread3 = new Thread(stringTask);
      thread3.setDaemon(true);
      thread3.start();

    } catch (Exception e) {
      e.printStackTrace();
      updateMyoStatus("Error: " + e.getMessage());
    }
  }

  public void connectAnalyzer() {}

  private void updateMyoStatus(final String msg) {
    myoStatus.setText("Myo: " + msg);
  }

  private String mapRemoteAddress(AsynchronousSocketChannel channel) {
    try {
      return channel.getRemoteAddress().toString();
    } catch (IOException e) {
      return "Unknown connection";
    }
  }
}
 public Stack() {
   elementsProperty.set(FXCollections.observableList(new ArrayList<>()));
 }
Exemplo n.º 19
0
  @Override
  public void start(Stage primaryStage) {
    CheckBox wrapToggle = new CheckBox("Wrap");
    wrapToggle.setSelected(true);
    area.wrapTextProperty().bind(wrapToggle.selectedProperty());
    Button undoBtn = createButton("undo", () -> area.undo());
    Button redoBtn = createButton("redo", () -> area.redo());
    Button cutBtn = createButton("cut", () -> area.cut());
    Button copyBtn = createButton("copy", () -> area.copy());
    Button pasteBtn = createButton("paste", () -> area.paste());
    Button boldBtn = createButton("bold", () -> toggleBold());
    Button italicBtn = createButton("italic", () -> toggleItalic());
    Button underlineBtn = createButton("underline", () -> toggleUnderline());
    Button strikeBtn = createButton("strikethrough", () -> toggleStrikethrough());
    ComboBox<Integer> sizeCombo =
        new ComboBox<>(
            FXCollections.observableArrayList(
                5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 48, 56, 64,
                72));
    sizeCombo.getSelectionModel().select(Integer.valueOf(12));
    ComboBox<String> familyCombo = new ComboBox<>(FXCollections.observableList(Font.getFamilies()));
    familyCombo.getSelectionModel().select("Serif");
    ColorPicker textColorPicker = new ColorPicker(Color.BLACK);
    ColorPicker backgroundColorPicker = new ColorPicker();

    sizeCombo.setOnAction(evt -> updateFontSize(sizeCombo.getValue()));
    familyCombo.setOnAction(evt -> updateFontFamily(familyCombo.getValue()));
    textColorPicker.valueProperty().addListener((o, old, color) -> updateTextColor(color));
    backgroundColorPicker
        .valueProperty()
        .addListener((o, old, color) -> updateBackgroundColor(color));

    undoBtn.disableProperty().bind(Bindings.not(area.undoAvailableProperty()));
    redoBtn.disableProperty().bind(Bindings.not(area.redoAvailableProperty()));

    BooleanBinding selectionEmpty =
        new BooleanBinding() {
          {
            bind(area.selectionProperty());
          }

          @Override
          protected boolean computeValue() {
            return area.getSelection().getLength() == 0;
          }
        };

    cutBtn.disableProperty().bind(selectionEmpty);
    copyBtn.disableProperty().bind(selectionEmpty);

    area.beingUpdatedProperty()
        .addListener(
            (o, old, beingUpdated) -> {
              if (!beingUpdated) {
                boolean bold, italic, underline, strike;
                Integer fontSize;
                String fontFamily;
                Color textColor;
                Color backgroundColor;

                IndexRange selection = area.getSelection();
                if (selection.getLength() != 0) {
                  StyleSpans<StyleInfo> styles = area.getStyleSpans(selection);
                  bold = styles.styleStream().anyMatch(s -> s.bold.orElse(false));
                  italic = styles.styleStream().anyMatch(s -> s.italic.orElse(false));
                  underline = styles.styleStream().anyMatch(s -> s.underline.orElse(false));
                  strike = styles.styleStream().anyMatch(s -> s.strikethrough.orElse(false));
                  int[] sizes =
                      styles
                          .styleStream()
                          .mapToInt(s -> s.fontSize.orElse(-1))
                          .distinct()
                          .toArray();
                  fontSize = sizes.length == 1 ? sizes[0] : -1;
                  String[] families =
                      styles
                          .styleStream()
                          .map(s -> s.fontFamily.orElse(null))
                          .distinct()
                          .toArray(i -> new String[i]);
                  fontFamily = families.length == 1 ? families[0] : null;
                  Color[] colors =
                      styles
                          .styleStream()
                          .map(s -> s.textColor.orElse(null))
                          .distinct()
                          .toArray(i -> new Color[i]);
                  textColor = colors.length == 1 ? colors[0] : null;
                  Color[] backgrounds =
                      styles
                          .styleStream()
                          .map(s -> s.backgroundColor.orElse(null))
                          .distinct()
                          .toArray(i -> new Color[i]);
                  backgroundColor = backgrounds.length == 1 ? backgrounds[0] : null;
                } else {
                  int p = area.getCurrentParagraph();
                  int col = area.getCaretColumn();
                  StyleInfo style = area.getStyleAtPosition(p, col);
                  bold = style.bold.orElse(false);
                  italic = style.italic.orElse(false);
                  underline = style.underline.orElse(false);
                  strike = style.strikethrough.orElse(false);
                  fontSize = style.fontSize.orElse(-1);
                  fontFamily = style.fontFamily.orElse(null);
                  textColor = style.textColor.orElse(null);
                  backgroundColor = style.backgroundColor.orElse(null);
                }

                updatingToolbar.suspendWhile(
                    () -> {
                      if (bold) {
                        if (!boldBtn.getStyleClass().contains("pressed")) {
                          boldBtn.getStyleClass().add("pressed");
                        }
                      } else {
                        boldBtn.getStyleClass().remove("pressed");
                      }

                      if (italic) {
                        if (!italicBtn.getStyleClass().contains("pressed")) {
                          italicBtn.getStyleClass().add("pressed");
                        }
                      } else {
                        italicBtn.getStyleClass().remove("pressed");
                      }

                      if (underline) {
                        if (!underlineBtn.getStyleClass().contains("pressed")) {
                          underlineBtn.getStyleClass().add("pressed");
                        }
                      } else {
                        underlineBtn.getStyleClass().remove("pressed");
                      }

                      if (strike) {
                        if (!strikeBtn.getStyleClass().contains("pressed")) {
                          strikeBtn.getStyleClass().add("pressed");
                        }
                      } else {
                        strikeBtn.getStyleClass().remove("pressed");
                      }

                      if (fontSize != -1) {
                        sizeCombo.getSelectionModel().select(fontSize);
                      } else {
                        sizeCombo.getSelectionModel().clearSelection();
                      }

                      if (fontFamily != null) {
                        familyCombo.getSelectionModel().select(fontFamily);
                      } else {
                        familyCombo.getSelectionModel().clearSelection();
                      }

                      if (textColor != null) {
                        textColorPicker.setValue(textColor);
                      }

                      backgroundColorPicker.setValue(backgroundColor);
                    });
              }
            });

    HBox panel1 = new HBox(3.0);
    HBox panel2 = new HBox(3.0);
    panel1
        .getChildren()
        .addAll(
            wrapToggle,
            undoBtn,
            redoBtn,
            cutBtn,
            copyBtn,
            pasteBtn,
            boldBtn,
            italicBtn,
            underlineBtn,
            strikeBtn);
    panel2.getChildren().addAll(sizeCombo, familyCombo, textColorPicker, backgroundColorPicker);

    VBox vbox = new VBox();
    VBox.setVgrow(area, Priority.ALWAYS);
    vbox.getChildren().addAll(panel1, panel2, area);

    Scene scene = new Scene(vbox, 600, 400);
    scene.getStylesheets().add(RichText.class.getResource("rich-text.css").toExternalForm());
    primaryStage.setScene(scene);
    area.requestFocus();
    primaryStage.setTitle("Rich Text Demo");
    primaryStage.show();
  }
Exemplo n.º 20
0
 @Override
 public ObservableList<BookingDetail> getDetails() {
   return FXCollections.observableList(newDetails.isEmpty() ? service.getDetails(id) : newDetails);
 }
Exemplo n.º 21
0
  @Override
  public void initialize(URL url, ResourceBundle rb) {
    loading.setVisible(false);
    checkTodos.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent t) {
            boolean checked = ((CheckBox) t.getTarget()).isSelected();
            for (Node node : servicos.getChildren()) {
              ((CheckBox) node).setSelected(checked);
            }
          }
        });
    unidades.setItems(FXCollections.observableList(new ArrayList<ComboboxItem>()));
    unidades.setOnAction(
        new EventHandler() {
          @Override
          public void handle(Event t) {
            loading.setVisible(true);
            checkTodos.setSelected(false);
            ComboBox cb = (ComboBox) t.getTarget();
            cb.getSelectionModel().selectedItemProperty();
            ComboboxItem item =
                (ComboboxItem) cb.getSelectionModel().selectedItemProperty().getValue();
            if (item != null && Integer.parseInt(item.getKey()) > 0) {
              unidadeAtual = Integer.parseInt(item.getKey());
              updateServicos(main.getService().buscarServicos(unidadeAtual));
            }
            loading.setVisible(false);
          }
        });
    buscar.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent t) {
            loading.setVisible(true);
            servicos.getChildren().clear();
            unidadeAtual = 0;
            try {
              main.getService()
                  .loadUrls(
                      servidor.getText(),
                      new Runnable() {
                        @Override
                        public void run() {
                          updateUnidades(main.getService().buscarUnidades());
                          loading.setVisible(false);
                        }
                      });
            } catch (Exception e) {
              loading.setVisible(false);
            }
          }
        });
    salvar.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent t) {
            loading.setVisible(true);
            try {
              List<Integer> idServicos = new ArrayList<Integer>();
              for (Node node : servicos.getChildren()) {
                if (((CheckBox) node).isSelected()) {
                  try {
                    String id = node.getId().split("-")[1];
                    idServicos.add(Integer.parseInt(id));
                  } catch (Exception e) {
                  }
                }
              }
              PainelConfig config = main.getConfig();
              config.get(PainelConfig.KEY_SERVER).setValue(servidor.getText());
              config.get(PainelConfig.KEY_UNIDADE, Integer.class).setValue(unidadeAtual);
              config
                  .get(PainelConfig.KEY_SERVICOS, Integer[].class)
                  .setValue(idServicos.toArray(new Integer[0]));
              // som e tema
              config.get(PainelConfig.KEY_SCREENSAVER_URL).setValue(videoUrl.getText());
              config
                  .get(PainelConfig.KEY_LANGUAGE)
                  .setValue(
                      ((ComboboxItem) language.getSelectionModel().getSelectedItem()).getKey());
              config
                  .get(PainelConfig.KEY_SOUND_VOICE, Boolean.class)
                  .setValue(vocalizar.isSelected());
              config.get(PainelConfig.KEY_COR_FUNDO).setValue(colorToHex(corFundo.getValue()));
              config
                  .get(PainelConfig.KEY_COR_MENSAGEM)
                  .setValue(colorToHex(corMensagem.getValue()));
              config.get(PainelConfig.KEY_COR_SENHA).setValue(colorToHex(corSenha.getValue()));
              config.get(PainelConfig.KEY_COR_GUICHE).setValue(colorToHex(corGuiche.getValue()));
              // screensaver layout
              config
                  .get(PainelConfig.KEY_SCREENSAVER_LAYOUT, Integer.class)
                  .setValue(
                      Integer.parseInt(((RadioButton) svLayout.getSelectedToggle()).getText()));
              config.save();

              main.getService().register(servidor.getText());
            } catch (Exception e) {
              e.printStackTrace();
            }
            loading.setVisible(false);
          }
        });
    exibirPainel.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent t) {
            main.getPainel().show();
          }
        });
    // language
    language.setItems(FXCollections.observableList(new ArrayList<ComboboxItem>()));
    SortedSet<String> keys = new TreeSet<String>(Main.locales.keySet());
    for (String key : keys) {
      language.getItems().add(new ComboboxItem(key, Main.locales.get(key)));
      if (Locale.getDefault().getLanguage().equals(key)) {
        main.getConfig().get(PainelConfig.KEY_LANGUAGE).setValue(Locale.getDefault().getLanguage());
      }
    }
    String defaultLang = main.getConfig().get(PainelConfig.KEY_LANGUAGE).getValue();
    for (Object item : language.getItems()) {
      if (defaultLang.equals(((ComboboxItem) item).getKey())) {
        language.getSelectionModel().select(item);
        break;
      }
    }
    language.setOnAction(
        new EventHandler() {
          @Override
          public void handle(Event t) {
            ComboBox cb = (ComboBox) t.getTarget();
            cb.getSelectionModel().selectedItemProperty();
            ComboboxItem item =
                (ComboboxItem) cb.getSelectionModel().selectedItemProperty().getValue();
            main.getConfig().get(PainelConfig.KEY_LANGUAGE).setValue(item.getKey());
          }
        });
    // video
    monitorId.setItems(FXCollections.observableList(new ArrayList<ComboboxItem>()));
    Integer defaultId = main.getConfig().get(PainelConfig.KEY_MONITOR_ID, Integer.class).getValue();
    for (int i = 0; i < Screen.getScreens().size(); i++) {
      StringBuilder sb = new StringBuilder();
      Rectangle2D b = Screen.getScreens().get(i).getBounds();
      sb.append(i + 1)
          .append(" (")
          .append(b.getWidth())
          .append(" x ")
          .append(b.getHeight())
          .append(")");
      ComboboxItem item = new ComboboxItem(i, sb.toString());
      monitorId.getItems().add(item);
      if (defaultId.equals(i)) {
        monitorId.getSelectionModel().select(item);
      }
    }
    monitorId.setOnAction(
        new EventHandler() {
          @Override
          public void handle(Event t) {
            ComboBox cb = (ComboBox) t.getTarget();
            cb.getSelectionModel().selectedItemProperty();
            ComboboxItem item =
                (ComboboxItem) cb.getSelectionModel().selectedItemProperty().getValue();
            Integer key = Integer.parseInt(item.getKey());
            if (key >= 0 && key < Screen.getScreens().size()) {
              main.getConfig().get(PainelConfig.KEY_MONITOR_ID, Integer.class).setValue(key);
            }
          }
        });
    // screen saver
    screenSaverTimeout.setItems(FXCollections.observableList(new ArrayList<ComboboxItem>()));
    Integer defaultTimeout =
        main.getConfig().get(PainelConfig.KEY_SCREENSAVER_TIMEOUT, Integer.class).getValue();
    SortedSet<Integer> keys2 = new TreeSet<Integer>(Main.intervals.keySet());
    for (Integer key : keys2) {
      ComboboxItem item = new ComboboxItem(key, Main.intervals.get(key));
      screenSaverTimeout.getItems().add(item);
      if (defaultTimeout.equals(key)) {
        screenSaverTimeout.getSelectionModel().select(item);
      }
    }
    screenSaverTimeout.setOnAction(
        new EventHandler() {
          @Override
          public void handle(Event t) {
            ComboBox cb = (ComboBox) t.getTarget();
            cb.getSelectionModel().selectedItemProperty();
            ComboboxItem item =
                (ComboboxItem) cb.getSelectionModel().selectedItemProperty().getValue();
            main.getConfig()
                .get(PainelConfig.KEY_SCREENSAVER_TIMEOUT, Integer.class)
                .setValue(Integer.parseInt(item.getKey()));
          }
        });
    fileChooser.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            FileChooser fileChooser = new FileChooser();
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("MP4", "*.mp4"));
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("AVI", "*.avi"));
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("HLS", "*.m3u8"));
            try {
              File file = fileChooser.showOpenDialog(null);
              videoUrl.setText(file.toURI().toString());
            } catch (Exception e) {
            }
          }
        });
    testVideo.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            try {
              String url = videoUrl.getText();
              if (url != null && !url.isEmpty()) {
                if (tester != null) {
                  tester.destroy();
                }
                tester = new VideoTester(url.trim());
                Stage painelStage = new Stage();
                painelStage.initOwner(stage);
                painelStage.setOnCloseRequest(
                    new EventHandler<WindowEvent>() {
                      @Override
                      public void handle(WindowEvent t) {
                        tester.destroy();
                      }
                    });
                tester.start(painelStage);
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        });
    // screesaver layout - marcando o padrao
    try {
      int id = main.getConfig().get(PainelConfig.KEY_SCREENSAVER_LAYOUT, Integer.class).getValue();
      svLayout.getToggles().get(id - 1).setSelected(true);
    } catch (Exception e) {
    }
    // criando stage
    this.stage = new Stage();
    stage.setTitle("Painel | Novo SGA");
    stage.setScene(new Scene(getRoot()));
    // so esconde se suportar systray
    if (SystemTray.isSupported()) {
      final Controller self = this;
      stage.setOnCloseRequest(
          new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent t) {
              self.stage.hide();
            }
          });
    }
  }
  /**
   * Series edition
   *
   * @param series Series to edit
   */
  void editSeries(final Series series) {
    String[] style = series.getStyle().split(";");
    String strColor = "black";
    final TextField editWidth = new TextField();

    String tempS = "null";
    for (String e : style) {
      if (e.contains("color: ")) {
        strColor = e.replace("color: ", "");
      } else if (e.contains("width: ")) {
        editWidth.setText(e.replace("width: ", ""));
      } else if (e.contains("shape: ")) {
        tempS = e.replace("shape: ", "");
      }
    }
    final String symbol = tempS;

    final List<SeriesShape> symbolList = new ArrayList<>();
    final ObservableList<SeriesShape> symbolListModel;
    final ListView<SeriesShape> comboSymbol = new ListView();
    symbolList.add(new SeriesShape("null", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("rectangle", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("circle", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("triangle", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("crux", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("diamond", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("empty rectangle", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("empty circle", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("empty triangle", javafx.scene.paint.Color.web(strColor)));
    symbolList.add(new SeriesShape("empty diamond", javafx.scene.paint.Color.web(strColor)));

    symbolListModel = FXCollections.observableList(symbolList);
    comboSymbol.setItems(symbolListModel);
    comboSymbol.setCellFactory(
        new Callback<ListView<SeriesShape>, ListCell<SeriesShape>>() {
          @Override
          public ListCell<SeriesShape> call(ListView<SeriesShape> p) {
            ListCell<SeriesShape> cell =
                new ListCell<SeriesShape>() {
                  @Override
                  protected void updateItem(SeriesShape t, boolean bln) {
                    super.updateItem(t, bln);
                    if (t != null) {
                      setText("");
                      setGraphic(t.getShapeGraphic());
                    }
                  }
                };

            return cell;
          }
        });
    for (SeriesShape smb : symbolListModel) {
      if (smb.getName().equals(symbol)) {
        comboSymbol.getSelectionModel().select(smb);
      }
    }

    final ColorPicker colorPicker = new ColorPicker(javafx.scene.paint.Color.web(strColor));

    colorPicker.setOnAction(
        (ActionEvent t) -> {
          String sc = colorPicker.getValue().toString();
          symbolListModel.clear();
          symbolListModel.add(new SeriesShape("null", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("rectangle", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("circle", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("triangle", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("crux", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("diamond", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("empty rectangle", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("empty circle", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("empty triangle", javafx.scene.paint.Color.web(sc)));
          symbolListModel.add(new SeriesShape("empty diamond", javafx.scene.paint.Color.web(sc)));

          comboSymbol.setItems(symbolListModel);
          for (SeriesShape smb : symbolListModel) {
            if (smb.getName().equals(symbol)) {
              comboSymbol.getSelectionModel().select(smb);
            }
          }
        });

    GridPane grid = new GridPane();

    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(0, 10, 0, 10));

    grid.add(new Label("Series"), 0, 0);
    grid.add(new Label(series.getKey().toString()), 1, 0);
    grid.add(new Label("Color"), 0, 1);
    grid.add(colorPicker, 1, 1);
    grid.add(new Label("Width"), 0, 2);
    grid.add(editWidth, 1, 2);
    grid.add(new Label("Shape"), 0, 3);
    grid.add(comboSymbol, 1, 3);

    new PseudoModalDialog(skeleton, grid, true) {
      @Override
      public boolean validation() {
        String strColor = colorPicker.getValue().toString();
        String strWidth = editWidth.getText();
        double dWidth = Double.valueOf(strWidth);
        String strSimbolo = "null";
        SeriesShape simb =
            new SeriesShape(
                comboSymbol.getSelectionModel().getSelectedItem().toString(),
                javafx.scene.paint.Color.web(strColor));

        XYItemRenderer renderer = (XYItemRenderer) plot.getRenderer(series.getAxisIndex());

        renderer.setSeriesPaint(series.getSeriesIndex(), scene2awtColor(colorPicker.getValue()));

        try {
          if (Double.valueOf(strWidth) > 0) {
            ((XYLineAndShapeRenderer) renderer)
                .setSeriesLinesVisible(series.getSeriesIndex(), true);
            renderer.setSeriesStroke(
                series.getSeriesIndex(), new BasicStroke(Integer.valueOf(strWidth)));
          } else {
            ((XYLineAndShapeRenderer) renderer)
                .setSeriesLinesVisible(series.getSeriesIndex(), false);
          }
        } catch (NumberFormatException ex) {

        }

        if (simb.getName().contains("null")) {
          ((XYLineAndShapeRenderer) renderer)
              .setSeriesShapesVisible(series.getSeriesIndex(), false);
          renderer.setSeriesShape(series.getSeriesIndex(), null);
        } else {
          ((XYLineAndShapeRenderer) renderer).setSeriesShapesVisible(series.getSeriesIndex(), true);
          renderer.setSeriesShape(series.getSeriesIndex(), simb.getShapeAWT());
          if (simb.getName().contains("empty")) {
            ((XYLineAndShapeRenderer) renderer)
                .setSeriesShapesFilled(series.getSeriesIndex(), false);
          } else {
            ((XYLineAndShapeRenderer) renderer)
                .setSeriesShapesFilled(series.getSeriesIndex(), true);
          }
        }

        series.setStyle(
            "color: "
                + strColor
                + ";width: "
                + editWidth.getText()
                + ";shape: "
                + strSimbolo
                + ";");

        for (Node le : legendFrame.getChildren()) {
          if (le instanceof LegendAxis) {
            for (Node nn : ((LegendAxis) le).getChildren()) {
              if (nn instanceof Label) {
                if (((Label) nn).getText().equals(series.getKey().toString())) {
                  ((Label) nn).setGraphic(simb.getShapeGraphic());
                }
              }
            }
          }
        }
        return true;
      }
    }.show();
  }
Exemplo n.º 23
0
 /** @param list */
 public ListSpinner(java.util.List<T> list) {
   this(FXCollections.observableList(list));
 }
Exemplo n.º 24
0
 public FontCombo() {
   super(FXCollections.observableList(Font.getFamilies()));
   getSelectionModel().select(defaultFont());
 }
 /**
  * Calls a {@link HistoryAnalyser#searchForAchievementsInHistory() searchForAchievementsInHistory}
  * method in <code>HistoryAnalyser</code> and populates the <code>achievementListView</code> with
  * the <code>ArrayList</code> of <code>String</code> returned.
  */
 private void showAchievementsInListView() {
   ArrayList<String> achievementNames = HistoryAnalyser.searchForAchievementsInHistory();
   achievementListView.setItems(FXCollections.observableList(achievementNames));
 }