/**
  * Add the given history to the entry (uses AutocompleteMenuUpdater if non-null).
  *
  * @param entry
  */
 public void updateHistory(final String entry) {
   if (updater != null) updater.updateHistory(entry);
   else { // add entry to top of menu items (for the particular autocomplete menu instance)
     // (Currently, there are two instances of this class in the editor: one for the inline editor,
     // one for the palette)
     final List<MenuItem> items = menu.getItems();
     // remove entry if present, to avoid duplication
     items.removeIf((item) -> item.getText().equals(entry));
     items.add(0, createMenuItem(entry));
   }
 }
  private Node createExportActions() {
    final Button button = new Button("Export", GlyphRegistry.get(AwesomeIcon.CARET_DOWN));
    button.getStyleClass().add("flat-button");

    // create menu
    final ContextMenu contextMenu = new ContextMenu();

    // csv chart
    MenuItem item = new MenuItem("Graph");
    item.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            export();
          }
        });
    contextMenu.getItems().add(item);
    button.setOnMousePressed(
        new EventHandler<Event>() {
          @Override
          public void handle(Event event) {
            contextMenu.show(button, Side.BOTTOM, 0, 0);
          }
        });

    return button;
  }
 /*     */ protected void handleControlPropertyChanged(String paramString) /*     */ {
   /*  72 */ super.handleControlPropertyChanged(paramString);
   /*  73 */ if (paramString == "DEFAULT_BUTTON") {
     /*  74 */ setDefaultButton(((Button) getSkinnable()).isDefaultButton());
     /*     */ }
   /*  76 */ else if (paramString == "CANCEL_BUTTON") {
     /*  77 */ setCancelButton(((Button) getSkinnable()).isCancelButton());
     /*     */ }
   /*  79 */ else if (paramString == "FOCUSED") {
     /*  80 */ if (!((Button) getSkinnable()).isFocused()) {
       /*  81 */ ContextMenu localContextMenu = ((Button) getSkinnable()).getContextMenu();
       /*  82 */ if ((localContextMenu != null) && /*  83 */ (localContextMenu.isShowing())) {
         /*  84 */ localContextMenu.hide();
         /*  85 */ Utils.removeMnemonics(localContextMenu, ((Button) getSkinnable()).getScene());
         /*     */ }
       /*     */ }
     /*     */ }
   /*  89 */ else if ((paramString == "PARENT")
       &&
       /*  90 */ (((Button) getSkinnable()).getParent() == null)
       && (getScene() != null)) {
     /*  91 */ if (((Button) getSkinnable()).isDefaultButton()) {
       /*  92 */ getScene().getAccelerators().remove(this.defaultAcceleratorKeyCodeCombination);
       /*     */ }
     /*  94 */ if (((Button) getSkinnable()).isCancelButton())
       /*  95 */ getScene().getAccelerators().remove(this.cancelAcceleratorKeyCodeCombination);
     /*     */ }
   /*     */ }
Exemple #4
0
 private ContextMenu createContextMenu() {
   ContextMenu menu = new ContextMenu();
   if (action != null) menu.setOnAction(action);
   menu.getItems().setAll(items);
   items = menu.getItems();
   return menu;
 }
Exemple #5
0
 private MenuBuilder(ContextMenu menu) {
   this.items = menu.getItems();
   this.text = null;
   this.action = menu.getOnAction();
   menuObj = null;
   ctxMenuObj = menu;
 }
 private ContextMenu createContextMenu(final TableRow<T> row) {
   ContextMenu menu = new ContextMenu();
   ContextMenu tableMenu = row.getTableView().getContextMenu();
   if (tableMenu != null) {
     menu.getItems().addAll(tableMenu.getItems());
     menu.getItems().add(new SeparatorMenuItem());
   }
   menu.getItems().addAll(menuItemFactory.call(row.getItem()));
   return menu;
 }
  private Node createAxisOptions() {
    final Button btn = new Button("Axis", GlyphRegistry.get(AwesomeIcon.CARET_DOWN));
    btn.getStyleClass().add("flat-button");

    final ContextMenu menu = new ContextMenu();
    btn.setOnMousePressed(
        new EventHandler<Event>() {
          @Override
          public void handle(Event event) {
            menu.show(btn, Side.BOTTOM, 0, 0);
          }
        });

    MenuItem item = new MenuItem("Y linear", GlyphRegistry.get(AwesomeIcon.CHECK));
    item.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            _chart.axisMode().set(CyclistAxis.Mode.LINEAR);
          }
        });
    item.getGraphic()
        .visibleProperty()
        .bind(Bindings.equal(_chart.axisMode(), CyclistAxis.Mode.LINEAR));
    menu.getItems().add(item);

    item = new MenuItem("Y log", GlyphRegistry.get(AwesomeIcon.CHECK));
    item.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            _chart.axisMode().set(CyclistAxis.Mode.LOG);
          }
        });
    item.getGraphic()
        .visibleProperty()
        .bind(Bindings.equal(_chart.axisMode(), CyclistAxis.Mode.LOG));
    item.disableProperty().bind(Bindings.equal(_chart.getMode(), InventoryChart.ChartMode.STACKED));
    menu.getItems().add(item);

    item = new MenuItem("Y force zero", GlyphRegistry.get(AwesomeIcon.CHECK));
    item.getGraphic().visibleProperty().bind(_chart.forceZero());
    item.disableProperty().bind(Bindings.equal(_chart.getMode(), InventoryChart.ChartMode.STACKED));
    menu.getItems().add(item);
    item.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent e) {
            _chart.forceZero().set(!_chart.forceZero().get());
          }
        });

    return btn;
  }
  public void mount() {
    ContextMenu menu = new ContextMenu();

    MenuItem menuItem;
    for (Operation operation : operations.getOperations()) {
      menuItem = new MenuItem(operation.getName());
      menuItem.setOnAction((event) -> operation.getAction().accept(event));
      menu.getItems().add(menuItem);
    }

    control.setContextMenu(menu);
  }
  /**
   * Populate the pop-up box.
   *
   * @param index - index of the task
   * @param task - task to be displayed
   */
  private void populatePopup(int index, Task task) {
    ArrayList<String> displayList = getDisplayItems(index, task);
    ArrayList<CustomMenuItem> menuItems = new ArrayList<CustomMenuItem>();

    for (int i = 0; i < displayList.size(); i++) {
      String str = displayList.get(i);
      Label label = new Label(str);
      CustomMenuItem item = new CustomMenuItem(label, true);

      item.setOnAction(
          new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
              replaceText(str);
              positionCaret(str.length());
            }
          });

      menuItems.add(item);
    }

    popupMenu.getItems().clear();
    popupMenu.getItems().addAll(menuItems);
  }
Exemple #10
0
  private void showContextMenu(double x, double y) {
    if (contextMenu != null && contextMenu.isShowing()) contextMenu.hide();
    contextMenu = new ContextMenu();
    // contextMenu.getStyleClass().add("background");

    Color bg = cfg.colorProperty().getValue();
    Color fg = bg.getBrightness() < 0.5f ? Color.WHITE : Color.BLACK;

    contextMenu.setStyle(background(bg, true));

    contextMenu.setOnHidden(
        value -> {
          if (cfg.autoHideProperty().get() && !arePopupsOpen()) maybeHideDock();
        });
    if (!cfg.autoHideProperty().get()) {
      MenuItem hide = new MenuItem(resources.getString("menu.hide"));
      hide.setOnAction(value -> getStage().setIconified(true));
      hide.setStyle(textFill(fg));
      contextMenu.getItems().add(hide);
    }
    MenuItem close = new MenuItem(resources.getString("menu.exit"));
    close.setOnAction(
        value -> {
          context.confirmExit();
          maybeHideDock();
        });
    close.setStyle(textFill(fg));
    contextMenu.getItems().add(close);
    Point2D loc = new Point2D(x + getStage().getX(), y + getStage().getY());
    contextMenu.show(dockContent, loc.getX(), loc.getY());
  }
Exemple #11
0
 @FXML
 private void evtMouseClick(MouseEvent evt) throws Exception {
   if (evt.getButton() == MouseButton.SECONDARY) {
     showContextMenu(evt.getX(), evt.getY());
     evt.consume();
   } else if (contextMenu != null) {
     contextMenu.hide();
   }
 }
Exemple #12
0
 @FXML
 private void evtMouseExit(MouseEvent evt) throws Exception {
   stopDockRevealerTimer();
   if (cfg.autoHideProperty().get()
       && !arePopupsOpen()
       && (contextMenu == null || !contextMenu.isShowing())) {
     maybeHideDock();
     evt.consume();
   }
 }
 public void removeFields() {
   menu.hide();
   current_field = null;
   synchronized (fields) {
     for (ControlWrapper cw : fields) {
       cw.unbind();
       fields.remove(cw);
     }
   }
 }
 void setupPlaylistsContextMenu() {
   ContextMenu cm = playlistsContextMenu;
   MenuItem createOffline =
       menuItem(
           res.getString("create_offline_playlist"),
           () -> {
             createOfflinePlaylist();
           });
   MenuItem setAsFeatured =
       menuItem(
           res.getString("set_as_featured"),
           () -> {
             Playlist selectedPlaylist =
                 (Playlist) playlistsView.getSelectionModel().getSelectedItem();
             if (selectedPlaylist != null) {
               rememberedPlaylist = selectedPlaylist;
               Settings.rememberedPlaylistId = selectedPlaylist.getId();
               infoLabel.setText(
                   String.format(res.getString("featured_set"), selectedPlaylist.getTitle()));
             }
           });
   MenuItem rename =
       menuItem(
           "(...) " + res.getString("rename_playlist"),
           () -> {
             renamePlaylist();
           });
   MenuItem delete =
       menuItem(
           "(-) " + res.getString("delete_playlist"),
           () -> {
             deletePlaylist();
           });
   cm.getItems()
       .addAll(
           createOffline,
           new SeparatorMenuItem(),
           setAsFeatured,
           new SeparatorMenuItem(),
           rename,
           delete);
 }
 /** Remove the auto-completed field from the menu's list of monitored controls */
 public void removeField(final TextInputControl control) {
   if (current_field != null && current_field.equals(control)) {
     menu.hide();
     current_field = null;
   }
   synchronized (fields) {
     for (ControlWrapper cw : fields) {
       if (cw.field.equals(control)) {
         cw.unbind();
         fields.remove(cw);
         break;
       }
     }
   }
 }
  @Override
  public void handle(MouseEvent event) {
    EventType<? extends MouseEvent> eventType = event.getEventType();
    if (eventType.equals(MouseEvent.MOUSE_CLICKED)) {
      if (openMenu != null) disposeOpenMenu();
      MenuItem hmi = new MenuItem("Help");
      hmi.setOnAction(e -> DialogService.openHelpDialog());

      PhongMaterial m = new PhongMaterial();
      m.setDiffuseColor(Color.GREEN);
      m.setSpecularColor(Color.WHITE);
      Box box = new Box(10, 10, 10);
      box.setMaterial(m);
      box.getTransforms().addAll(new Rotate(45, Rotate.Z_AXIS), new Rotate(45, Rotate.X_AXIS));

      MenuItem imi = new MenuItem("Inspect", new ImageView(Resources.SEARCH_ICON));
      imi.setOnAction(
          e -> {
            DialogService.openInspectDialog(node);
          });

      MenuItem emi = new MenuItem("Expand / Collapse", box);
      emi.setOnAction(
          e -> {
            handlePrimaryClick();
          });

      openMenu = new ContextMenu();
      openMenu.getItems().addAll(emi, imi, new SeparatorMenuItem(), hmi);
      openMenu.show(shape, event.getScreenX(), event.getScreenY());
    } else if (eventType.equals(MouseEvent.MOUSE_ENTERED)) {
      manager.submitTask(() -> manager.findReferingNodes(node, true));
    } else if (eventType.equals(MouseEvent.MOUSE_EXITED)) {
      manager.submitTask(() -> manager.findReferingNodes(node, false));
    }
  }
Exemple #17
0
  public CellLien(Map<String, Comportement> comportements, Comportement comportement, String name) {
    MenuItem delete = new MenuItem("Delete");
    menu.getItems().add(delete);
    this.id = ((ComportementLogique) comportements.get(name)).getId();
    delete.setOnAction(
        t -> {
          if (!getItem().isEmpty()) {
            Lien lien = getTableView().getItems().get(getIndex());
            comportement.getSortant(id).remove(lien);
            Lien entrant = lien.getComportement().getSiginalE(id, comportement);
            lien.getComportement().getEntrant(id).remove(entrant);
            getTableView().getItems().remove(getIndex());
          }
        });
    setContextMenu(menu);
    setOnMouseClicked(
        e -> {
          if (e.getClickCount() == 2 && (!isEmpty())) {
            Stage sousStage = new Stage();
            FXMLLoader loader = new FXMLLoader();
            try {
              loader.setLocation(DrawBoardController.class.getResource("NewLogiqueLien.fxml"));
              AnchorPane page = (AnchorPane) loader.load();

              NewLogiqueLienController controller = loader.getController();

              controller.setStage(sousStage);
              controller.setComportements(comportements);
              controller.setComportement(
                  comportement,
                  ((Lien) getTableRow().getItem()).getComportement(),
                  ((ComportementLogique) comportements.get(name)));
              Scene scene = new Scene(page);
              sousStage.setScene(scene);

              sousStage.showAndWait();
            } catch (IOException ex) {
              ex.printStackTrace();
            }
          }
        });
  }
  /**
   * Set the results for the provider with the given label at the given index.
   *
   * @param label Label for results provider or category
   * @param results List of results to be shown
   * @param index Expected index (with respect to labels) of results
   */
  public void setResults(final String label, final List<String> results, int index) {
    if (label == null) return;

    // System.out.println("results for " + label + " at " + index);

    final List<MenuItem> items = new LinkedList<MenuItem>();

    synchronized (result_list) {
      final ListIterator<Result> it = result_list.listIterator();
      Result result;
      if (it.hasNext()) {
        result = it.next();
        while (result.expected < index) {
          if (result.textIs(label)) it.remove();
          else result.addItemsTo(items);
          if (it.hasNext()) result = it.next();
          else break;
        }
        if (result.expected >= index && it.hasPrevious()) it.previous();
        else result.addItemsTo(items);
      }
      result = new Result(label, results, index);
      it.add(result);
      result.addItemsTo(items);
      while (it.hasNext()) {
        result = it.next();
        if (result.expected <= index) result.expected++;
        if (result.expected >= index) index++;
        if (result.textIs(label)) it.remove();
        else result.addItemsTo(items);
      }
    }

    // for (Result result : result_list)
    // System.out.println(result);

    // Must make changes to JavaFX ContextMenu object from JavaFX thread
    Platform.runLater(() -> menu.getItems().setAll(items));
  }
 public AutocompleteMenu() {
   // The drop-down menu which lists suggestions happens
   // to capture ENTER keys.
   //
   // When user types PV name into current_field and presses ENTER,
   // the menu captures that ENTER key and uses it to hide the menu.
   // --> Need to send ENTER down to current_field.
   //
   // If user selects one of the suggested menu items
   // and presses enter, menu item will update the current_field
   // --> Need to send ENTER down to current_field _after_
   //     the menu item updated current_field.
   menu.addEventFilter(
       KeyEvent.KEY_PRESSED,
       event -> {
         if (event.getCode() == KeyCode.ENTER && current_field != null)
           Platform.runLater(
               () -> {
                 if (current_field != null) Event.fireEvent(current_field, event);
               });
       });
 }
Exemple #20
0
  public Browser(final Stage stage) {
    // apply the styles
    getStyleClass().add("browser");

    for (int i = 0; i < captions.length; i++) {
      // create hyperlinks
      Hyperlink hpl = hpls[i] = new Hyperlink(captions[i]);
      Image image = images[i] = new Image(getClass().getResourceAsStream(imageFiles[i]));
      hpl.setGraphic(new ImageView(image));
      final String url = urls[i];
      final boolean addButton = (hpl.getText().equals("Help"));

      // process event
      hpl.setOnAction(
          (ActionEvent e) -> {
            needDocumentationButton = addButton;
            webEngine.load(url);
          });
    }

    comboBox.setPrefWidth(60);

    // create the toolbar
    toolBar = new HBox();
    toolBar.setAlignment(Pos.CENTER);
    toolBar.getStyleClass().add("browser-toolbar");
    toolBar.getChildren().add(comboBox);
    toolBar.getChildren().addAll(hpls);
    toolBar.getChildren().add(createSpacer());

    // set action for the button
    toggleHelpTopics.setOnAction(
        (ActionEvent t) -> {
          webEngine.executeScript("toggle_visibility('help_topics')");
        });

    smallView.setPrefSize(120, 80);

    // handle popup windows
    webEngine.setCreatePopupHandler(
        (PopupFeatures config) -> {
          smallView.setFontScale(0.8);
          if (!toolBar.getChildren().contains(smallView)) {
            toolBar.getChildren().add(smallView);
          }
          return smallView.getEngine();
        });

    // process history
    final WebHistory history = webEngine.getHistory();
    history
        .getEntries()
        .addListener(
            (Change<? extends Entry> c) -> {
              c.next();
              c.getRemoved()
                  .stream()
                  .forEach(
                      (e) -> {
                        comboBox.getItems().remove(e.getUrl());
                      });
              c.getAddedSubList()
                  .stream()
                  .forEach(
                      (e) -> {
                        comboBox.getItems().add(e.getUrl());
                      });
            });

    // set the behavior for the history combobox
    comboBox.setOnAction(
        (Event ev) -> {
          int offset = comboBox.getSelectionModel().getSelectedIndex() - history.getCurrentIndex();
          history.go(offset);
        });

    // process page loading
    webEngine
        .getLoadWorker()
        .stateProperty()
        .addListener(
            (ObservableValue<? extends State> ov, State oldState, State newState) -> {
              toolBar.getChildren().remove(toggleHelpTopics);
              if (newState == State.SUCCEEDED) {
                JSObject win = (JSObject) webEngine.executeScript("window");
                win.setMember("app", new JavaApp());
                if (needDocumentationButton) {
                  toolBar.getChildren().add(toggleHelpTopics);
                }
              }
            });
    // adding context menu
    final ContextMenu cm = new ContextMenu();
    MenuItem cmItem1 = new MenuItem("Print");
    cm.getItems().add(cmItem1);
    toolBar.addEventHandler(
        MouseEvent.MOUSE_CLICKED,
        (MouseEvent e) -> {
          if (e.getButton() == MouseButton.SECONDARY) {
            cm.show(toolBar, e.getScreenX(), e.getScreenY());
          }
        });

    // processing print job
    cmItem1.setOnAction(
        (ActionEvent e) -> {
          PrinterJob job = PrinterJob.createPrinterJob();
          if (job != null) {
            webEngine.print(job);
            job.endJob();
          }
        });

    // load the home page
    webEngine.load("http://www.cnn.com");

    // add components
    getChildren().add(toolBar);
    getChildren().add(browser);
  }
Exemple #21
0
  private Node createModeActions() {
    final Button button = new Button("Options", GlyphRegistry.get(AwesomeIcon.CARET_DOWN));
    button.getStyleClass().add("flat-button");

    // create menu
    final ContextMenu contextMenu = new ContextMenu();

    // line chart
    MenuItem item = new MenuItem("Line chart", GlyphRegistry.get(AwesomeIcon.CHECK));
    item.getGraphic()
        .visibleProperty()
        .bind(Bindings.equal(_chart.getMode(), InventoryChart.ChartMode.LINE));
    item.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            _chart.setMode(InventoryChart.ChartMode.LINE);
            if (!_lastForceZero) _chart.forceZero().set(false);
            if (_saveAxisMode == CyclistAxis.Mode.LOG) _chart.axisMode().set(CyclistAxis.Mode.LOG);
          }
        });
    contextMenu.getItems().add(item);

    //		// area chart
    //		item = new MenuItem("Area chart");
    //		item.setOnAction(new EventHandler<ActionEvent>() {
    //			@Override
    //			public void handle(ActionEvent event) {
    //				_chart.setMode(InventoryChart.ChartMode.AREA);
    //			}
    //		});
    //		contextMenu.getItems().add(item);

    // stacked chart
    item = new MenuItem("Stacked chart", GlyphRegistry.get(AwesomeIcon.CHECK));
    item.getGraphic()
        .visibleProperty()
        .bind(Bindings.equal(_chart.getMode(), InventoryChart.ChartMode.STACKED));
    item.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            _lastForceZero = _chart.forceZero().get();
            if (!_lastForceZero) _chart.forceZero().set(true);
            _saveAxisMode = _chart.axisMode().get();
            _chart.setMode(InventoryChart.ChartMode.STACKED);
          }
        });
    contextMenu.getItems().add(item);

    contextMenu.getItems().add(new SeparatorMenuItem());

    MenuItem checked = new MenuItem("Show total", GlyphRegistry.get(AwesomeIcon.CHECK));
    checked.getGraphic().visibleProperty().bind(_chart.getShowTotal());
    checked.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            _chart.setShowTotal(!_chart.getShowTotal().getValue());
          }
        });
    contextMenu.getItems().add(checked);

    button.setOnMousePressed(
        new EventHandler<Event>() {
          @Override
          public void handle(Event event) {
            contextMenu.show(button, Side.BOTTOM, 0, 0);
          }
        });

    return button;
  }
Exemple #22
0
  public PathTreeCell(/*final Stage owner, */ final StringProperty messageProp) {
    this.messageProp = messageProp;
    MenuItem expandMenu = new MenuItem("Expand");
    expandMenu.setOnAction(
        (ActionEvent event) -> {
          getTreeItem().setExpanded(true);
        });
    MenuItem expandAllMenu = new MenuItem("Expand All");
    expandAllMenu.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent t) {
            expandTreeItem(getTreeItem());
          }

          private void expandTreeItem(TreeItem<PathItem> item) {
            if (item.isLeaf()) {
              return;
            }
            item.setExpanded(true);
            ObservableList<TreeItem<PathItem>> children = item.getChildren();
            children
                .stream()
                .filter(child -> (!child.isLeaf()))
                .forEach(child -> expandTreeItem(child));
          }
        });
    MenuItem addMenu = new MenuItem("Add Directory");
    addMenu.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent t) {
            Path newDir = createNewDirectory();
            if (newDir != null) {
              TreeItem<PathItem> addItem = PathTreeItem.createNode(new PathItem(newDir));
              getTreeItem().getChildren().add(addItem);
            }
          }

          private Path createNewDirectory() {
            Path newDir = null;
            while (true) {
              Path path = getTreeItem().getValue().getPath();
              newDir =
                  Paths.get(
                      path.toAbsolutePath().toString(),
                      "newDirectory" + String.valueOf(getItem().getCountNewDir()));
              try {
                Files.createDirectory(newDir);
                break;
              } catch (FileAlreadyExistsException ex) {
                continue;
              } catch (IOException ex) {
                cancelEdit();
                messageProp.setValue(
                    String.format("Creating directory(%s) failed", newDir.getFileName()));
                break;
              }
            }
            return newDir;
          }
        });
    MenuItem deleteMenu = new MenuItem("Delete");
    deleteMenu.setOnAction(
        (ActionEvent event) -> {
          ObjectProperty<TreeItem<PathItem>> prop = new SimpleObjectProperty<>();
          new ModalDialog(/*owner, */ getTreeItem(), prop);
          prop.addListener(
              (ObservableValue<? extends TreeItem<PathItem>> ov,
                  TreeItem<PathItem> oldItem,
                  TreeItem<PathItem> newItem) -> {
                try {
                  Files.walkFileTree(newItem.getValue().getPath(), new VisitorForDelete());
                  if (getTreeItem().getParent() == null) {
                    // when the root is deleted how to clear the TreeView???
                  } else {
                    getTreeItem().getParent().getChildren().remove(newItem);
                  }
                } catch (IOException ex) {
                  messageProp.setValue(
                      String.format(
                          "Deleting %s failed", newItem.getValue().getPath().getFileName()));
                }
              });
        });
    dirMenu.getItems().addAll(expandMenu, expandAllMenu, deleteMenu, addMenu);
    fileMenu.getItems().addAll(deleteMenu);
  }
Exemple #23
0
  public void init() {
    currentEditor.addListener(
        (observable, oldValue, newValue) -> {
          canUndo.unbind();
          canRedo.unbind();
          if (newValue != null) {
            currentEditorIsXHTML.setValue(
                currentEditor.getValue().getMediaType().equals(MediaType.XHTML));
            canUndo.bind(currentEditor.getValue().canUndoProperty());
            canRedo.bind(currentEditor.getValue().canRedoProperty());
          } else {
            currentEditorIsXHTML.setValue(false);
            canUndo.setValue(false);
            canRedo.setValue(false);
          }
        });

    MenuItem separatorItem = new SeparatorMenuItem();
    // Html menu
    contextMenuXHTML = new ContextMenu();
    contextMenuXHTML.setAutoFix(true);
    contextMenuXHTML.setAutoHide(true);

    Menu clipsItem = new Menu("Clips");
    clipManager
        .getClipsRoot()
        .addEventHandler(
            TreeItem.<Clip>childrenModificationEvent(),
            event -> {
              clipsItem.getItems().clear();
              writeClipMenuItemChildren(clipManager.getClipsRoot(), clipsItem);
            });
    contextMenuXHTML.getItems().add(clipsItem);
    contextMenuXHTML.getItems().add(separatorItem);

    MenuItem itemRepairHTML = new MenuItem("HTML reparieren");
    itemRepairHTML.setOnAction(
        e -> {
          beautifyOrRepairHTML("repair");
        });
    contextMenuXHTML.getItems().add(itemRepairHTML);

    MenuItem itemBeautifyHTML = new MenuItem("HTML formatieren");
    itemBeautifyHTML.setOnAction(
        e -> {
          beautifyOrRepairHTML("format");
        });
    contextMenuXHTML.getItems().add(itemBeautifyHTML);

    contextMenuXHTML.getItems().add(separatorItem);

    MenuItem openInExternalBrowserItem = new MenuItem("In externem Browser öffnen");
    openInExternalBrowserItem.setOnAction(
        e -> {
          openInExternalBrowser(currentEditor);
        });
    contextMenuXHTML.getItems().add(openInExternalBrowserItem);

    // XML menu
    contextMenuXML = new ContextMenu();
    contextMenuXML.setAutoFix(true);
    contextMenuXML.setAutoHide(true);

    MenuItem generateUuidMenuItem = new MenuItem("Neue UUID generieren");
    generateUuidMenuItem.setOnAction(
        e -> {
          book.getMetadata().generateNewUuid();
          bookBrowserManager.refreshOpf();
        });
    contextMenuXML.getItems().add(generateUuidMenuItem);
    currentXMLResource.addListener(
        new ChangeListener<Resource>() {
          @Override
          public void changed(
              ObservableValue<? extends Resource> observable,
              Resource oldValue,
              Resource newValue) {
            if (newValue != null
                && currentXMLResource.get().mediaTypeProperty().getValue().equals(MediaType.OPF)) {
              generateUuidMenuItem.visibleProperty().setValue(true);
            } else {
              generateUuidMenuItem.visibleProperty().setValue(false);
            }
          }
        });

    MenuItem separatorItem2 = new SeparatorMenuItem();
    contextMenuXML.getItems().add(separatorItem2);
    separatorItem2.visibleProperty().bind(generateUuidMenuItem.visibleProperty());

    MenuItem itemRepairXML = new MenuItem("XML reparieren");
    itemRepairXML.setOnAction(
        e -> {
          beautifyOrRepairXML("repair");
        });
    contextMenuXML.getItems().add(itemRepairXML);

    MenuItem itemBeautifyXML = new MenuItem("XML formatieren");
    itemBeautifyXML.setOnAction(
        e -> {
          beautifyOrRepairXML("format");
        });
    contextMenuXML.getItems().add(itemBeautifyXML);

    // css menu
    contextMenuCSS = new ContextMenu();
    contextMenuCSS.setAutoFix(true);
    contextMenuCSS.setAutoHide(true);
    MenuItem formatCSSOneLineItem = new MenuItem("Styles in je einer Zeile formatieren");
    formatCSSOneLineItem.setOnAction(e -> beautifyCSS("one_line"));
    contextMenuCSS.getItems().add(formatCSSOneLineItem);

    MenuItem formatCSSMultipleLinesItem = new MenuItem("Styles in mehreren Zeilen formatieren");
    formatCSSMultipleLinesItem.setOnAction(e -> beautifyCSS("multiple_lines"));
    contextMenuCSS.getItems().add(formatCSSMultipleLinesItem);
  }
  void setupTracksContextMenu() {
    ContextMenu cm = tracksContextMenu;
    List<MenuItem> items = cm.getItems();
    items.clear();

    Playlist pl = getSelectedPlaylist();
    if (pl == null) {
      items.add(
          menuItem(
              "-> " + res.getString("add_to"),
              () -> {
                menuAddToPlaylist();
              }));
      if (rememberedPlaylist != null) {
        items.add(
            menuItem(
                "-> "
                    + String.format(
                        res.getString("add_to_featured"), rememberedPlaylist.getTitle()),
                () -> {
                  Track t = getSelectedTrack();
                  if (t != null) {
                    addToPlaylist(t, rememberedPlaylist);
                  }
                }));
      }
    } else {
      items.add(
          menuItem(
              "(+) " + res.getString("add_files"),
              () -> {
                FileChooser fileChooser = new FileChooser();
                fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
                fileChooser.setTitle(String.format(res.getString("add_files_to"), pl.getTitle()));
                fileChooser
                    .getExtensionFilters()
                    .addAll(new FileChooser.ExtensionFilter("MP3", "*.mp3"));
                List<File> files = fileChooser.showOpenMultipleDialog(null);
                if (files != null) {
                  addToPlaylist(files, pl);
                }
              }));
      items.add(
          menuItem(
              "(+) " + res.getString("add_folder_recursively"),
              () -> {
                DirectoryChooser dirChooser = new DirectoryChooser();
                dirChooser.setTitle(String.format(res.getString("add_folder_to"), pl.getTitle()));
                dirChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
                File dir = dirChooser.showDialog(null);
                if (dir == null) return;
                Collection<File> files = FileUtils.listFiles(dir, new String[] {"mp3"}, true);
                addToPlaylist(new ArrayList(files), pl);
              }));
      items.add(new SeparatorMenuItem());
      if (rememberedPlaylist != null)
        items.add(
            menuItem(
                "-> "
                    + String.format(
                        res.getString("add_to_featured"), rememberedPlaylist.getTitle()),
                () -> {
                  Track t = getSelectedTrack();
                  if (t != null) addToPlaylist(t, rememberedPlaylist);
                }));
      items.add(
          menuItem(
              "-> " + res.getString("add_to"),
              () -> {
                menuAddToPlaylist();
              }));
      items.add(new SeparatorMenuItem());
      items.add(
          menuItem(
              "(...) " + res.getString("rename_track"),
              () -> {
                renameTrack();
              }));
      items.add(new SeparatorMenuItem());
      items.add(
          menuItem(
              "(-) " + res.getString("delete_track") + pl.getTitle(),
              () -> {
                deleteTrackFromPlaylist();
              }));
      items.add(
          menuItem(
              "(-) " + res.getString("delete_dead_items"),
              () -> {
                Track t = getSelectedTrack();
                if (t == null) {
                  return;
                }
                deleteDeadFromOfflinePlaylist(pl);
              }));
    }
  }
  /** This method initializes the DateColumn */
  private void initializeDateTable() {
    // initialize datetable
    dateTable.setEditable(true);
    dateTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    ;

    ContextMenu menu = new ContextMenu();
    MenuItem holidayChanger = new MenuItem("Holiday");
    MenuItem summerChanger = new MenuItem("Summer Day");
    MenuItem schoolDayChanger = new MenuItem("School Day");
    MenuItem weekendChanger = new MenuItem("Weekend");
    holidayChanger.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            dateTable.getSelectionModel().getSelectedItem().setDayType(DayType.HOLIDAY);
            updateDayType(dateTable.getSelectionModel().getSelectedItems(), DayType.HOLIDAY);
            // update Column
            dateTable.getColumns().get(1).setVisible(false);
            dateTable.getColumns().get(1).setVisible(true);
            dailyDayTypeChartPanel.addNewSeries(dailyIntervalData);
          }
        });

    summerChanger.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            dateTable.getSelectionModel().getSelectedItem().setDayType(DayType.SUMMER_DAY);
            updateDayType(dateTable.getSelectionModel().getSelectedItems(), DayType.SUMMER_DAY);
            // update Column
            dateTable.getColumns().get(1).setVisible(false);
            dateTable.getColumns().get(1).setVisible(true);
            dailyDayTypeChartPanel.addNewSeries(dailyIntervalData);
          }
        });

    schoolDayChanger.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            dateTable.getSelectionModel().getSelectedItem().setDayType(DayType.SCHOOL_DAY);
            updateDayType(dateTable.getSelectionModel().getSelectedItems(), DayType.SCHOOL_DAY);
            // update Column
            dateTable.getColumns().get(1).setVisible(false);
            dateTable.getColumns().get(1).setVisible(true);
            dailyDayTypeChartPanel.addNewSeries(dailyIntervalData);
          }
        });

    weekendChanger.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            dateTable.getSelectionModel().getSelectedItem().setDayType(DayType.WEEKEND);
            updateDayType(dateTable.getSelectionModel().getSelectedItems(), DayType.WEEKEND);
            // update Column
            dateTable.getColumns().get(1).setVisible(false);
            dateTable.getColumns().get(1).setVisible(true);
            dailyDayTypeChartPanel.addNewSeries(dailyIntervalData);
          }
        });

    menu.getItems().add(holidayChanger);
    menu.getItems().add(summerChanger);
    menu.getItems().add(schoolDayChanger);
    menu.getItems().add(weekendChanger);

    dateTable.setContextMenu(menu);

    dateColumn.setCellValueFactory(
        cellData -> Assistant.parsePropertiesString(cellData.getValue().getDate().toString()));

    dayTypeColumn.setCellValueFactory(
        cellData -> Assistant.parsePropertiesString(cellData.getValue().getDayType().toString()));
  }
 /** Show pop-up menu. */
 public void showPopup() {
   if (!popupMenu.isShowing()) {
     popupMenu.show(this, Side.BOTTOM, 0, 0);
   }
 }
Exemple #27
0
 public static void addMenuItem(ContextMenu menu, String text, EventHandler<ActionEvent> action) {
   MenuItem item = new MenuItem(text);
   if (action != null) item.setOnAction(action);
   menu.getItems().add(item);
 }
 private void disposeOpenMenu() {
   openMenu.hide();
   openMenu = null;
 }
Exemple #29
0
 public static void addMenuSeparator(ContextMenu menu) {
   menu.getItems().add(new SeparatorMenuItem());
 }
  /**
   * @param name Chart name
   * @param parent Skeleton parent
   * @param axes Configuration of axes
   * @param abcissaName Abcissa name
   */
  public SwingChart(String name, final Skeleton parent, List<AxisChart> axes, String abcissaName) {
    this.skeleton = parent;
    this.axes = axes;
    this.name = name;

    this.abcissaFormat = NumberFormat.getInstance(Locale.getDefault());
    this.ordinateFormat = NumberFormat.getInstance(Locale.getDefault());

    plot = new XYPlot();
    plot.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strChartBackgroundColor)));
    plot.setDomainGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setRangeGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    abcissaAxis = new NumberAxis(abcissaName);
    ((NumberAxis) abcissaAxis).setAutoRangeIncludesZero(false);
    abcissaAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setAutoRange(true);
    abcissaAxis.setLowerMargin(0.0);
    abcissaAxis.setUpperMargin(0.0);
    abcissaAxis.setTickLabelsVisible(true);
    abcissaAxis.setLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));
    abcissaAxis.setTickLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));

    plot.setDomainAxis(abcissaAxis);

    for (int i = 0; i < axes.size(); i++) {
      AxisChart categoria = axes.get(i);
      addAxis(categoria.getName());

      for (int j = 0; j < categoria.configSerieList.size(); j++) {
        SimpleSeriesConfiguration cs = categoria.configSerieList.get(j);
        addSeries(categoria.getName(), cs);
      }
    }
    chart = new JFreeChart("", new Font("SansSerif", Font.BOLD, 16), plot, false);

    chart.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(4, 4, 4, 4),
            BorderFactory.createLineBorder(
                scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)))));

    chartPanel.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escape");
    chartPanel
        .getActionMap()
        .put(
            "escape",
            new AbstractAction() {

              @Override
              public void actionPerformed(java.awt.event.ActionEvent e) {
                for (int i = 0; i < plot.getDatasetCount(); i++) {
                  XYDataset test = plot.getDataset(i);
                  XYItemRenderer r = plot.getRenderer(i);
                  r.removeAnnotations();
                }
              }
            });

    chartPanel.addChartMouseListener(
        cml =
            new ChartMouseListener() {
              @Override
              public void chartMouseClicked(ChartMouseEvent event) {}

              @Override
              public void chartMouseMoved(ChartMouseEvent event) {
                try {
                  XYItemEntity xyitem = (XYItemEntity) event.getEntity(); // get clicked entity
                  XYDataset dataset = (XYDataset) xyitem.getDataset(); // get data set
                  double x = dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem());
                  double y = dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem());

                  final XYPlot plot = chart.getXYPlot();
                  for (int i = 0; i < plot.getDatasetCount(); i++) {
                    XYDataset test = plot.getDataset(i);
                    XYItemRenderer r = plot.getRenderer(i);
                    r.removeAnnotations();
                    if (test == dataset) {
                      NumberAxis ejeOrdenada = AxesList.get(i);
                      double y_max = ejeOrdenada.getUpperBound();
                      double y_min = ejeOrdenada.getLowerBound();
                      double x_max = abcissaAxis.getUpperBound();
                      double x_min = abcissaAxis.getLowerBound();
                      double angulo;
                      if (y > (y_max + y_min) / 2 && x > (x_max + x_min) / 2) {
                        angulo = 3.0 * Math.PI / 4.0;
                      } else if (y > (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                        angulo = 1.0 * Math.PI / 4.0;
                      } else if (y < (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                        angulo = 7.0 * Math.PI / 4.0;
                      } else {
                        angulo = 5.0 * Math.PI / 4.0;
                      }

                      CircleDrawer cd =
                          new CircleDrawer(
                              (Color) r.getSeriesPaint(xyitem.getSeriesIndex()),
                              new BasicStroke(2.0f),
                              null);
                      // XYAnnotation bestBid = new
                      // XYDrawableAnnotation(dataset.getXValue(xyitem.getSeriesIndex(),
                      // xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(),
                      // xyitem.getItem()), 11, 11, cd);
                      String txt =
                          "X:" + abcissaFormat.format(x) + ", Y:" + ordinateFormat.format(y);
                      XYPointerAnnotation anotacion =
                          new XYPointerAnnotation(
                              txt,
                              dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()),
                              dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()),
                              angulo);
                      anotacion.setTipRadius(10.0);
                      anotacion.setBaseRadius(35.0);
                      anotacion.setFont(new Font("SansSerif", Font.PLAIN, 10));

                      if (Long.parseLong((strChartBackgroundColor.replace("#", "")), 16)
                          > 0xffffff / 2) {
                        anotacion.setPaint(Color.black);
                        anotacion.setArrowPaint(Color.black);
                      } else {
                        anotacion.setPaint(Color.white);
                        anotacion.setArrowPaint(Color.white);
                      }

                      // bestBid.setPaint((Color) r.getSeriesPaint(xyitem.getSeriesIndex()));
                      r.addAnnotation(anotacion);
                    }
                  }

                  // LabelValorVariable.setSize(LabelValorVariable.getPreferredSize());
                } catch (NullPointerException | ClassCastException ex) {

                }
              }
            });

    chartPanel.setPopupMenu(null);
    chartPanel.setBackground(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    SwingNode sn = new SwingNode();
    sn.setContent(chartPanel);
    chartFrame = new VBox();
    chartFrame.getChildren().addAll(sn, legendFrame);
    VBox.setVgrow(sn, Priority.ALWAYS);
    VBox.setVgrow(legendFrame, Priority.NEVER);

    chartFrame
        .getStylesheets()
        .addAll(SwingChart.class.getResource("overlay-chart.css").toExternalForm());

    legendFrame.setStyle("marco: " + strBackgroundColor + ";-fx-background-color: marco;");

    MenuItem mi;
    mi = new MenuItem("Print");
    mi.setOnAction(
        (ActionEvent t) -> {
          print(chartFrame);
        });
    contextMenuList.add(mi);

    sn.setOnMouseClicked(
        (MouseEvent t) -> {
          if (menu != null) {
            menu.hide();
          }
          if (t.getClickCount() == 2) {
            backgroundEdition();
          }
        });

    mi = new MenuItem("Copy to clipboard");
    mi.setOnAction(
        (ActionEvent t) -> {
          copyClipboard(chartFrame);
        });
    contextMenuList.add(mi);

    mi = new MenuItem("Export values");
    mi.setOnAction(
        (ActionEvent t) -> {
          FileChooser fileChooser = new FileChooser();
          fileChooser.setTitle("Export to file");
          fileChooser
              .getExtensionFilters()
              .addAll(new FileChooser.ExtensionFilter("Comma Separated Values", "*.csv"));

          Window w = null;
          try {
            w = parent.getScene().getWindow();
          } catch (NullPointerException e) {

          }
          File file = fileChooser.showSaveDialog(w);
          if (file != null) {
            export(file);
          }
        });
    contextMenuList.add(mi);

    chartFrame.setOnContextMenuRequested(
        (ContextMenuEvent t) -> {
          if (menu != null) {
            menu.hide();
          }
          menu = new ContextMenu();
          menu.getItems().addAll(contextMenuList);
          menu.show(chartFrame, t.getScreenX(), t.getScreenY());
        });
  }