javafx.css.PseudoClass Java Examples

The following examples show how to use javafx.css.PseudoClass. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileTreeTable.java    From Lipi with MIT License 6 votes vote down vote up
private void prepare() {
        buildFileBrowserTreeTableView(treeTableView);

        final PseudoClass firstRowClass = PseudoClass.getPseudoClass("first-row");

        treeTableView.setRowFactory(treeTable -> {
            TreeTableRow<File> row = new TreeTableRow<File>();
            row.treeItemProperty().addListener((ov, oldTreeItem, newTreeItem) ->
                    row.pseudoClassStateChanged(firstRowClass, newTreeItem == treeTable.getRoot()));
            row.setContextMenu(rightClickContextMenu);
            return row;
        });

        treeTableView.setOnMouseClicked(
                new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                if (mouseEvent.getClickCount() == 2) {
                    openSelectedTreeitemInHmdEditor();
                }

            }
        });

//        this.getChildren().add(treeTableView);
    }
 
Example #2
Source File: CacheRow.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void updateItem(CacheItem item, boolean empty) {
  super.updateItem(item, empty);
  if (empty || item == null) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("hit"), false);
    pseudoClassStateChanged(PseudoClass.getPseudoClass("miss"), false);
  } else if (item != null && item.getState().indexOf("EMPTY") != -1) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("hit"), false);
    pseudoClassStateChanged(PseudoClass.getPseudoClass("miss"), false);
  } else if (item != null && item.getState().indexOf("HIT") != -1) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("hit"), true);
    pseudoClassStateChanged(PseudoClass.getPseudoClass("miss"), false);
  } else {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("hit"), false);
    pseudoClassStateChanged(PseudoClass.getPseudoClass("miss"), true);
  }
}
 
Example #3
Source File: NodeEditionCodeArea.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public IntFunction<javafx.scene.Node> defaultLineNumberFactory() {
    IntFunction<javafx.scene.Node> base = LineNumberFactory.get(this);
    Val<Integer> activePar = Val.wrap(currentParagraphProperty());

    return idx -> {

        javafx.scene.Node label = base.apply(idx);

        activePar.conditionOnShowing(label)
                 .values()
                 .subscribe(p -> label.pseudoClassStateChanged(PseudoClass.getPseudoClass("has-caret"), idx == p));

        // adds a pseudo class if part of the focus node appears on this line
        currentFocusNode.conditionOnShowing(label)
                        .values()
                        .subscribe(n -> label.pseudoClassStateChanged(PseudoClass.getPseudoClass("is-focus-node"),
                                                                      n != null && idx + 1 <= n.getEndLine() && idx + 1 >= n.getBeginLine()));

        return label;
    };
}
 
Example #4
Source File: XPathAutocompleteProvider.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Gets the index of the currently focused item. */
private int getFocusIdx() {
    if (!autoCompletePopup.isShowing()) {
        return -1;
    }

    List<ObservableSet<PseudoClass>> collect =
        autoCompletePopup.getItems()
                         .stream()
                         .map(this::getStyleableNode)
                         .filter(Objects::nonNull)
                         .map(Node::getPseudoClassStates)
                         .collect(Collectors.toList());

    for (int i = 0; i < collect.size(); i++) {
        if (collect.get(i).contains(PseudoClass.getPseudoClass("focused"))) {
            return i;
        }
    }

    return -1;
}
 
Example #5
Source File: TabTest.java    From WorkbenchFX with Apache License 2.0 6 votes vote down vote up
@Test
void testActiveTabListener() {
  PseudoClass selected = PseudoClass.getPseudoClass("selected");
  assertFalse(tab.isActiveTab());
  assertFalse(tab.getPseudoClassStates().contains(selected));

  // change it to be the active module tab
  activeModule.set(mockModules[0]);
  assertTrue(tab.isActiveTab());
  assertTrue(tab.getPseudoClassStates().contains(selected));

  // change the module displayed by this tab, should not be the active tab now
  tab.setModule(mockModules[1]);
  assertFalse(tab.isActiveTab());
  assertFalse(tab.getPseudoClassStates().contains(selected));

  // changing the active module tab now should make it active again
  activeModule.set(mockModules[1]);
  assertTrue(tab.isActiveTab());
  assertTrue(tab.getPseudoClassStates().contains(selected));

  verify(mockBench, atLeastOnce()).activeModuleProperty();
}
 
Example #6
Source File: TopicConfigView.java    From kafka-message-tool with MIT License 6 votes vote down vote up
private void setCssStyleAndToolTip(KafkaClusterProxy proxy, String topicName) {
    String toolTipMessage;
    PseudoClass psuedoClass;

    final boolean topicExists = proxy.hasTopic(topicName);
    if (topicExists) {
        psuedoClass = OK_TOPIC_EXISTS_PSEUDO_CLASS;
        toolTipMessage = String.format("Topic '%s' exists.", topicName);
    } else {

        if (proxy.isTopicAutoCreationEnabled() != TriStateConfigEntryValue.False) {
            psuedoClass = TOPIC_WILL_BE_AUTOCREATED_PSEUDO_CLASS;
            toolTipMessage = String.format("Topic '%s' does not exist yet " +
                            "but will be auto-created by first connected consumer/publisher.",
                    topicName);
        } else {
            psuedoClass = CANNOT_USE_TOPIC_PSEUDO_CLASS;
            toolTipMessage = String.format("Topic '%s' does not exists. Must be created manually.", topicName);
        }
    }

    topicNameField.pseudoClassStateChanged(psuedoClass, true);
    topicNameField.setTooltip(TooltipCreator.createFrom(toolTipMessage));
}
 
Example #7
Source File: ControlUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * By default text fields don't show the prompt when the caret is
 * inside the field, even if the text is empty.
 */
public static void makeTextFieldShowPromptEvenIfFocused(TextField field) {
    // See css

    Val.wrap(field.textProperty())
       .values()
       .withDefaultEvent(field.getText())
        .subscribe(text -> field.pseudoClassStateChanged(PseudoClass.getPseudoClass("empty-input"), StringUtils.isBlank(text)));

}
 
Example #8
Source File: VolumePopupController.java    From MusicPlayer with MIT License 5 votes vote down vote up
@FXML private void muteClick() {

		PseudoClass muted = PseudoClass.getPseudoClass("muted");
		boolean isMuted = mutedButton.isVisible();
		muteButton.setVisible(isMuted);
		mutedButton.setVisible(!isMuted);
		volumeSlider.pseudoClassStateChanged(muted, !isMuted);
		frontVolumeTrack.pseudoClassStateChanged(muted, !isMuted);
		volumeLabel.pseudoClassStateChanged(muted, !isMuted);
		MusicPlayer.mute(isMuted);
	}
 
Example #9
Source File: ProgressIndicatorTest2.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void start(Stage primaryStage) {
    StackPane root = new StackPane();
    ProgressIndicator pi = new ProgressIndicator();
    Task<Void> counter = new Task<Void>() {
        @Override
        public Void call() throws Exception {
            for (int i = 1; i <= 100; i++) {
                Thread.sleep(50);
                updateProgress(i, 100);
            }
            return null;
        }
    };
    pi.progressProperty().bind(counter.progressProperty());
    pi.progressProperty().addListener((obs, oldProgress, newProgress) -> {
        PseudoClass warning = PseudoClass.getPseudoClass("warning");
        PseudoClass critical = PseudoClass.getPseudoClass("critical");
        if (newProgress.doubleValue() < 0.3) {
            pi.pseudoClassStateChanged(warning, false);
            pi.pseudoClassStateChanged(critical, true);
        } else if (newProgress.doubleValue() < 0.65) {
            pi.pseudoClassStateChanged(warning, true);
            pi.pseudoClassStateChanged(critical, false);
        } else {
            pi.pseudoClassStateChanged(warning, false);
            pi.pseudoClassStateChanged(critical, false);
        }
    });
    pi.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
    root.setStyle("-fx-background-color: antiqueWhite;");
    root.getChildren().add(pi);
    Scene scene = new Scene(root, 400, 400);
    scene.getStylesheets().add("/css/progress.css");
    primaryStage.setScene(scene);
    primaryStage.show();
    new Thread(counter).start();
}
 
Example #10
Source File: MemoryRow.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void updateItem(MemoryItem item, boolean empty) {
  super.updateItem(item, empty);
  if (empty || item == null || Status.RUNNING.get()) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("updated"), false);
  } else if (item != null && item.updated()) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("updated"), true);
  } else {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("updated"), false);
  }
}
 
Example #11
Source File: TextRow.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void updateItem(StatementItem item, boolean empty) {
  super.updateItem(item, empty);
  if (empty || item == null || Status.RUNNING.get()) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("pc"), false);
  } else if (item != null && (Data.atoi(item.addressProperty().get()) == state.xregfile().getProgramCounter())) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("pc"), true);
  } else {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("pc"), false);
  }
}
 
Example #12
Source File: RegFileRow.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void updateItem(RegisterItem item, boolean empty) {
  super.updateItem(item, empty);
  if (empty || item == null || Status.RUNNING.get()) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("updated"), false);
  } else if (item != null && item.updated()) {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("updated"), true);
  } else {
    pseudoClassStateChanged(PseudoClass.getPseudoClass("updated"), false);
  }
}
 
Example #13
Source File: ListenerConfigView.java    From kafka-message-tool with MIT License 5 votes vote down vote up
private void configureMessageNameTextField() {
    listenerNameTextField.setText(config.getName());
    listenerNameTextField.textProperty().addListener((observableValue, s, newValue) -> {

        final PseudoClass errorClass = PseudoClass.getPseudoClass("error");
        listenerNameTextField.pseudoClassStateChanged(errorClass, true);
        if (ValidatorUtils.isStringIdentifierValid(newValue)) {
            config.setName(newValue.trim());
            listenerNameTextField.pseudoClassStateChanged(errorClass, false);
        }
        refreshCallback.run();
    });
}
 
Example #14
Source File: NodeDetailPaneInfo.java    From scenic-view with GNU General Public License v3.0 5 votes vote down vote up
private String getPseudoState(final Set<PseudoClass> states) {
    final StringBuilder sb = new StringBuilder();
    
    int i = 0;
    for (PseudoClass pseudoClass : states) {
        if (pseudoClass != null && ! pseudoClass.getPseudoClassName().isEmpty()) {
            if (i++ != 0) {
                sb.append(',');
            }
            sb.append(pseudoClass.getPseudoClassName());
        }
    }
    return sb.length() != 0 ? sb.toString() : Detail.EMPTY_DETAIL;
}
 
Example #15
Source File: SimpleControl.java    From PreferencesFX with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the css style for the defined properties.
 *
 * @param pseudo   The CSS pseudo class to toggle.
 * @param newValue Determines whether the CSS class should be applied.
 */
@Override
protected void updateStyle(PseudoClass pseudo, boolean newValue) {
  if (node != null) {
    node.pseudoClassStateChanged(pseudo, newValue);
  }
  if (fieldLabel != null) {
    fieldLabel.pseudoClassStateChanged(pseudo, newValue);
  }
}
 
Example #16
Source File: SmartPopover.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void registerPseudoClassListeners(SmartPopover popOver) {

        EventStreams.valuesOf(popOver.detachedProperty())
                    .subscribe(v -> popOver.pseudoClassStateChanged(PseudoClass.getPseudoClass("detached"), v));
        EventStreams.valuesOf(popOver.focusedProperty())
                    // JavaFX lacks a focus model that works across several popups and stuff.
                    // The only solution we have to avoid having duplicate carets or so, is
                    // to *not* let a popover that openly has textfields or other controls
                    // that steal focus *be detachable*
                    .subscribe(v -> popOver.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), v));

    }
 
Example #17
Source File: NodeEditionCodeArea.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * TODO does this need to be disableable? Maybe some keyboards use the CTRL key in ways I don't
 */
private void enableCtrlSelection() {

    final Val<Boolean> isNodeSelectionMode =
        ReactfxUtil.vetoableYes(getDesignerRoot().isCtrlDownProperty(), CTRL_SELECTION_VETO_PERIOD);

    addEventHandler(
        MouseOverTextEvent.MOUSE_OVER_TEXT_BEGIN,
        ev -> {
            if (!isNodeSelectionMode.getValue()) {
                return;
            }
            Node currentRoot = getService(DesignerRoot.AST_MANAGER).compilationUnitProperty().getValue();
            if (currentRoot == null) {
                return;
            }

            TextPos2D target = getPmdLineAndColumnFromOffset(this, ev.getCharacterIndex());

            findNodeAt(currentRoot, target)
                .map(n -> NodeSelectionEvent.of(n, new DataHolder().withData(CARET_POSITION, target)))
                .ifPresent(selectionEvts::push);
        }
    );


    isNodeSelectionMode.values().distinct().subscribe(isSelectionMode -> {
        pseudoClassStateChanged(PseudoClass.getPseudoClass("is-node-selection"), isSelectionMode);
        setMouseOverTextDelay(isSelectionMode ? NODE_SELECTION_HOVER_DELAY : null);
    });
}
 
Example #18
Source File: ControlUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * When the [boundProp] is blank, display instead the [defaultText]
 * as grayed.
 */
public static void bindLabelPropertyWithDefault(Label label, String defaultText, Val<String> boundProp) {
    Val<String> filteredContent = boundProp.filter(StringUtils::isNotBlank);
    label.textProperty().bind(filteredContent.orElseConst(defaultText));

    filteredContent.values().subscribe(it -> label.pseudoClassStateChanged(PseudoClass.getPseudoClass("default-message"),
                                                                           it == null));

}
 
Example #19
Source File: DbgTraceView.java    From erlyberly with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void putTableColumns() {
    TableColumn<TraceLog,Long> seqColumn;
    seqColumn = new TableColumn<TraceLog,Long>("Seq.");
    seqColumn.setCellValueFactory(new PropertyValueFactory("instanceNum"));
    configureColumnWidth("seqColumnWidth", seqColumn);

    TableColumn<TraceLog,String> pidColumn;
    pidColumn = new TableColumn<TraceLog,String>("Pid");
    pidColumn.setCellValueFactory(new PropertyValueFactory("pidString"));
    configureColumnWidth("pidColumnWidth", pidColumn);

    TableColumn<TraceLog,String> regNameColumn;
    regNameColumn = new TableColumn<TraceLog,String>("Reg. Name");
    regNameColumn.setCellValueFactory(new PropertyValueFactory("regName"));
    configureColumnWidth("regNameColumnWidth", regNameColumn);

    TableColumn<TraceLog,String> durationNameColumn;
    durationNameColumn = new TableColumn<TraceLog,String>("Duration (microseconds)");
    durationNameColumn.setCellValueFactory(new PropertyValueFactory("duration"));
    configureColumnWidth("durationNameColumnWidth", durationNameColumn);

    TableColumn<TraceLog,String> functionNameColumn;
    functionNameColumn = new TableColumn<TraceLog,String>("Function");
    functionNameColumn.setCellValueFactory(new PropertyValueFactory("function"));
    configureColumnWidth("functionNameColumnWidth", functionNameColumn);

    TableColumn<TraceLog,String> argsColumn;
    argsColumn = new TableColumn<TraceLog,String>("Args");
    argsColumn.setCellValueFactory(new PropertyValueFactory("args"));
    configureColumnWidth("argsColumnWidth", argsColumn);

    TableColumn<TraceLog,String> resultColumn;
    resultColumn = new TableColumn<TraceLog,String>("Result");
    resultColumn.setCellValueFactory(new PropertyValueFactory("result"));
    configureColumnWidth("resultColumnWidth", resultColumn);

    tracesBox.getColumns().setAll(
        seqColumn, pidColumn, regNameColumn, durationNameColumn, functionNameColumn, argsColumn, resultColumn
    );

    // based on http://stackoverflow.com/questions/27015961/tableview-row-style
    PseudoClass exceptionClass = PseudoClass.getPseudoClass("exception");
    PseudoClass notCompletedClass = PseudoClass.getPseudoClass("not-completed");
    PseudoClass breakerRowClass = PseudoClass.getPseudoClass("breaker-row");
    tracesBox.setRowFactory(tv -> {
        TableRow<TraceLog> row = new TableRow<>();
        ChangeListener<Boolean> completeListener = (obs, oldComplete, newComplete) -> {
            row.pseudoClassStateChanged(exceptionClass, row.getItem().isExceptionThrower());
            row.pseudoClassStateChanged(notCompletedClass, !row.getItem().isComplete());
        };
        row.itemProperty().addListener((obs, oldTl, tl) -> {
            if (oldTl != null) {
                oldTl.isCompleteProperty().removeListener(completeListener);
            }
            if (tl != null) {

                row.pseudoClassStateChanged(notCompletedClass, !row.getItem().isComplete());
                if("breaker-row".equals(tl.getCssClass())) {
                    row.pseudoClassStateChanged(breakerRowClass, true);

                    row.pseudoClassStateChanged(exceptionClass, false);
                    row.pseudoClassStateChanged(notCompletedClass, false);
                }
                else {
                    tl.isCompleteProperty().addListener(completeListener);
                    row.pseudoClassStateChanged(breakerRowClass, false);
                    row.pseudoClassStateChanged(exceptionClass, tl.isExceptionThrower());
                }
            }
            else {
                row.pseudoClassStateChanged(exceptionClass, false);
                row.pseudoClassStateChanged(notCompletedClass, false);
                row.pseudoClassStateChanged(breakerRowClass, false);
            }
        });
        return row ;
    });
}
 
Example #20
Source File: ResponsiveHandler.java    From ResponsiveFX with Apache License 2.0 4 votes vote down vote up
private static void removeAllPseudoClasses(Node n) {
    for (PseudoClass pseudoClass : DeviceType.getAllClasses()) {
        n.pseudoClassStateChanged(pseudoClass, false);
    }
}
 
Example #21
Source File: ChatBubble.java    From dolphin-platform with Apache License 2.0 4 votes vote down vote up
private void setChatPseudoClass(PseudoClass cls, boolean value) {
    mainBubble.pseudoClassStateChanged(cls, value);
    mySpeakerSign.pseudoClassStateChanged(cls, value);
    oppositeSpeakerSign.pseudoClassStateChanged(cls, value);
}
 
Example #22
Source File: ArtistsController.java    From MusicPlayer with MIT License 4 votes vote down vote up
private VBox createCell(Artist artist) {

        VBox cell = new VBox();
        Label title = new Label(artist.getTitle());
        ImageView image = new ImageView(artist.getArtistImage());
        image.imageProperty().bind(artist.artistImageProperty());
        VBox imageBox = new VBox();

        title.setTextOverrun(OverrunStyle.CLIP);
        title.setWrapText(true);
        title.setPadding(new Insets(10, 0, 10, 0));
        title.setAlignment(Pos.TOP_LEFT);
        title.setPrefHeight(66);
        title.prefWidthProperty().bind(grid.widthProperty().subtract(100).divide(5).subtract(1));

        image.fitWidthProperty().bind(grid.widthProperty().subtract(100).divide(5).subtract(1));
        image.fitHeightProperty().bind(grid.widthProperty().subtract(100).divide(5).subtract(1));
        image.setPreserveRatio(true);
        image.setSmooth(true);

        imageBox.prefWidthProperty().bind(grid.widthProperty().subtract(100).divide(5).subtract(1));
        imageBox.prefHeightProperty().bind(grid.widthProperty().subtract(100).divide(5).subtract(1));
        imageBox.setAlignment(Pos.CENTER);
        imageBox.getChildren().add(image);

        cell.getChildren().addAll(imageBox, title);
        cell.setPadding(new Insets(10, 10, 0, 10));
        cell.getStyleClass().add("artist-cell");
        cell.setAlignment(Pos.CENTER);
        cell.setOnMouseClicked(event -> {

            MainController mainController = MusicPlayer.getMainController();
            ArtistsMainController artistsMainController = (ArtistsMainController) mainController.loadView("ArtistsMain");

            VBox artistCell = (VBox) event.getSource();
            String artistTitle = ((Label) artistCell.getChildren().get(1)).getText();
            Artist a = Library.getArtist(artistTitle);
            artistsMainController.selectArtist(a);
        });
        
        cell.setOnDragDetected(event -> {
        	PseudoClass pressed = PseudoClass.getPseudoClass("pressed");
        	cell.pseudoClassStateChanged(pressed, false);
        	Dragboard db = cell.startDragAndDrop(TransferMode.ANY);
        	ClipboardContent content = new ClipboardContent();
            content.putString("Artist");
            db.setContent(content);
        	MusicPlayer.setDraggedItem(artist);
        	db.setDragView(cell.snapshot(null, null), cell.widthProperty().divide(2).get(), cell.heightProperty().divide(2).get());
            event.consume();
        });

        return cell;
    }
 
Example #23
Source File: JFXSnackbar.java    From JFoenix with Apache License 2.0 4 votes vote down vote up
public PseudoClass getPseudoClass() {
    return pseudoClass;
}
 
Example #24
Source File: DockPane.java    From DockFX with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void handle(DockEvent event) {
  if (event.getEventType() == DockEvent.DOCK_ENTER) {
    if (!dockIndicatorOverlay.isShowing()) {
      Point2D topLeft = DockPane.this.localToScreen(0, 0);
      dockIndicatorOverlay.show(DockPane.this, topLeft.getX(), topLeft.getY());
    }
  } else if (event.getEventType() == DockEvent.DOCK_OVER) {
    this.receivedEnter = false;

    dockPosDrag = null;
    dockAreaDrag = dockNodeDrag;

    for (DockPosButton dockIndicatorButton : dockPosButtons) {
      if (dockIndicatorButton
          .contains(dockIndicatorButton.screenToLocal(event.getScreenX(), event.getScreenY()))) {
        dockPosDrag = dockIndicatorButton.getDockPos();
        if (dockIndicatorButton.isDockRoot()) {
          dockAreaDrag = root;
        }
        dockIndicatorButton.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), true);
        break;
      } else {
        dockIndicatorButton.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), false);
      }
    }

    if (dockPosDrag != null) {
      Point2D originToScene = dockAreaDrag.localToScene(0, 0).subtract(this.localToScene(0, 0));

      dockAreaIndicator.setVisible(true);
      dockAreaIndicator.relocate(originToScene.getX(), originToScene.getY());
      if (dockPosDrag == DockPos.RIGHT) {
        dockAreaIndicator.setTranslateX(dockAreaDrag.getLayoutBounds().getWidth() / 2);
      } else {
        dockAreaIndicator.setTranslateX(0);
      }

      if (dockPosDrag == DockPos.BOTTOM) {
        dockAreaIndicator.setTranslateY(dockAreaDrag.getLayoutBounds().getHeight() / 2);
      } else {
        dockAreaIndicator.setTranslateY(0);
      }

      if (dockPosDrag == DockPos.LEFT || dockPosDrag == DockPos.RIGHT) {
        dockAreaIndicator.setWidth(dockAreaDrag.getLayoutBounds().getWidth() / 2);
      } else {
        dockAreaIndicator.setWidth(dockAreaDrag.getLayoutBounds().getWidth());
      }
      if (dockPosDrag == DockPos.TOP || dockPosDrag == DockPos.BOTTOM) {
        dockAreaIndicator.setHeight(dockAreaDrag.getLayoutBounds().getHeight() / 2);
      } else {
        dockAreaIndicator.setHeight(dockAreaDrag.getLayoutBounds().getHeight());
      }
    } else {
      dockAreaIndicator.setVisible(false);
    }

    if (dockNodeDrag != null) {
      Point2D originToScreen = dockNodeDrag.localToScreen(0, 0);

      double posX = originToScreen.getX() + dockNodeDrag.getLayoutBounds().getWidth() / 2
          - dockPosIndicator.getWidth() / 2;
      double posY = originToScreen.getY() + dockNodeDrag.getLayoutBounds().getHeight() / 2
          - dockPosIndicator.getHeight() / 2;

      if (!dockIndicatorPopup.isShowing()) {
        dockIndicatorPopup.show(DockPane.this, posX, posY);
      } else {
        dockIndicatorPopup.setX(posX);
        dockIndicatorPopup.setY(posY);
      }

      // set visible after moving the popup
      dockPosIndicator.setVisible(true);
    } else {
      dockPosIndicator.setVisible(false);
    }
  }

  if (event.getEventType() == DockEvent.DOCK_RELEASED && event.getContents() != null) {
    if (dockPosDrag != null && dockIndicatorOverlay.isShowing()) {
      DockNode dockNode = (DockNode) event.getContents();
      dockNode.dock(this, dockPosDrag, dockAreaDrag);
    }
  }

  if ((event.getEventType() == DockEvent.DOCK_EXIT && !this.receivedEnter)
      || event.getEventType() == DockEvent.DOCK_RELEASED) {
    if (dockIndicatorPopup.isShowing()) {
      dockIndicatorOverlay.hide();
      dockIndicatorPopup.hide();
    }
  }
}
 
Example #25
Source File: EditionPresenter.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void initialize() {
    edition.setShowTransitionFactory(BounceInRightTransition::new);
    PseudoClass pseudoClassDisable = PseudoClass.getPseudoClass("disabled");
            
    edition.showingProperty().addListener((obs, oldValue, newValue) -> {
        if (newValue) {
            
            submit.disableProperty().unbind();
                
            Comment activeComment = service.activeCommentProperty().get();
            if (activeComment != null) {
                // disable avatar in case comment is not editable
                // content is enabled if user is its author
                commentsText.setDisable(!activeComment.getNetworkId().equals(service.getUser().getNetworkId()));
                avatar.pseudoClassStateChanged(pseudoClassDisable, commentsText.isDisable());
                avatar.setImage(Service.getUserImage(activeComment.getImageUrl()));
            
                authorText.setText(activeComment.getAuthor());
                commentsText.setText(activeComment.getContent());
                
                submit.setText("Apply");
                submit.disableProperty().bind(Bindings.createBooleanBinding(()->{
                    return authorText.textProperty()
                            .isEqualTo(activeComment.getAuthor())
                            .and(commentsText.textProperty()
                                    .isEqualTo(activeComment.getContent())).get();
                    }, authorText.textProperty(),commentsText.textProperty()));
                editMode = true;
            } else {
                commentsText.setDisable(false);
                avatar.pseudoClassStateChanged(pseudoClassDisable, false);
                avatar.setImage(Service.getUserImage(service.getUser().getPicture()));
                authorText.setText(service.getUser().getName());
                
                submit.setText("Submit");
                submit.disableProperty().bind(Bindings.createBooleanBinding(() -> {
                        return authorText.textProperty()
                                .isEmpty()
                                .or(commentsText.textProperty()
                                        .isEmpty()).get();
                    }, authorText.textProperty(), commentsText.textProperty()));
                editMode = false;
            }
            
            authorText.setDisable(!authorText.getText().isEmpty());
            
            AppBar appBar = getApp().getAppBar();
            appBar.setNavIcon(MaterialDesignIcon.MENU.button(e -> 
                    getApp().getDrawer().open()));
            appBar.setTitleText("Edition");
        } else {
            authorText.clear();
            commentsText.clear();
        }
    });
    
    Services.get(DisplayService.class)
            .ifPresent(d -> {
                if (d.isTablet()) {
                    avatar.getStyleClass().add("tablet");
                }
            });
    avatar.setImage(Service.getUserImage(service.getUser().getPicture()));
}
 
Example #26
Source File: FxDump.java    From FxDock with Apache License 2.0 4 votes vote down vote up
protected void dump(Node n)
{
	SB sb = new SB(4096);
	sb.nl();
	
	while(n != null)
	{
		sb.a(CKit.getSimpleName(n));
		
		String id = n.getId();
		if(CKit.isNotBlank(id))
		{
			sb.a(" #");
			sb.a(id);
		}
		
		for(String s: n.getStyleClass())
		{
			sb.a(" .").a(s);
		}
		
		for(PseudoClass c: n.getPseudoClassStates())
		{
			sb.a(" :").a(c);
		}
		
		sb.nl();
		
		if(n instanceof Text)
		{
			sb.sp(4);
			sb.a("text: ");
			sb.a(TextTools.escapeControlsForPrintout(((Text)n).getText()));
			sb.nl();
		}
		
		CList<CssMetaData<? extends Styleable,?>> md = new CList<>(n.getCssMetaData());
		sort(md);
		
		for(CssMetaData d: md)
		{
			String k = d.getProperty();
			Object v = d.getStyleableProperty(n).getValue();
			if(shouldShow(v))
			{
				Object val = describe(v);
				sb.sp(4).a(k);
				sb.sp().a(val);
				if(d.isInherits())
				{
					sb.a(" *");
				}
				sb.nl();
			}
		}
		
		n = n.getParent();
	}
	D.print(sb);
}
 
Example #27
Source File: DragAndDropUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Registers a {@link javafx.scene.Node} as the target of a drag and
 * drop initiated by {@link #registerAsNodeDragSource(javafx.scene.Node, Node, DesignerRoot)}.
 *
 * <p>While the mouse is over the target, the target will have the CSS
 * class {@link #NODE_DRAG_OVER}.
 *  @param target            Target UI component
 * @param nodeRangeConsumer Action to run with the {@link Dragboard} contents on success
 * @param root
 */
public static void registerAsNodeDragTarget(javafx.scene.Node target, Consumer<TextRange> nodeRangeConsumer, DesignerRoot root) {

    root.getService(DesignerRoot.IS_NODE_BEING_DRAGGED)
        .values()
        .subscribe(it -> target.pseudoClassStateChanged(PseudoClass.getPseudoClass("node-drag-possible-target"), it));


    target.setOnDragOver(evt -> {
        if (evt.getGestureSource() != target
            && evt.getDragboard().hasContent(NODE_RANGE_DATA_FORMAT)) {
            /* allow for both copying and moving, whatever user chooses */
            evt.acceptTransferModes(TransferMode.LINK);
        }
        evt.consume();
    });

    target.setOnDragEntered(evt -> {
        if (evt.getGestureSource() != target
            && evt.getDragboard().hasContent(NODE_RANGE_DATA_FORMAT)) {
            target.getStyleClass().addAll(NODE_DRAG_OVER);
        }
        evt.consume();
    });

    target.setOnDragExited(evt -> {
        target.getStyleClass().remove(NODE_DRAG_OVER);
        evt.consume();
    });

    target.setOnDragDropped(evt -> {

        boolean success = false;

        Dragboard db = evt.getDragboard();
        if (db.hasContent(NODE_RANGE_DATA_FORMAT)) {
            TextRange content = (TextRange) db.getContent(NODE_RANGE_DATA_FORMAT);
            nodeRangeConsumer.accept(content);
            success = true;
        }

        evt.setDropCompleted(success);

        evt.consume();
    });
}
 
Example #28
Source File: NodeHelper.java    From tornadofx-controls with Apache License 2.0 4 votes vote down vote up
public static void addPseudoClass( Node node, String className ){
    PseudoClass pseudoClass = PseudoClass.getPseudoClass( className );
    node.pseudoClassStateChanged( pseudoClass, true );
}
 
Example #29
Source File: NodeParentageCrumbBar.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * If the node is already displayed on the crumbbar, only sets the focus on it. Otherwise, sets
 * the node to be the deepest one of the crumb bar. Noop if node is null.
 */
@Override
public void setFocusNode(final Node newSelection, DataHolder options) {

    if (newSelection == null) {
        setSelectedCrumb(null);
        return;
    }

    if (Objects.equals(newSelection, currentSelection)) {
        return;
    }

    currentSelection = newSelection;

    boolean found = false;

    // We're trying to estimate the ratio of px/crumb,
    // to make an educated guess about how many crumbs we can fit
    // in case we need to call setDeepestNode
    int totalNumChar = 0;
    int totalNumCrumbs = 0;
    // the sum of children width is the actual width with overflow
    // the width of this control is the max acceptable width *without* overflow
    double totalChildrenWidth = 0;
    // constant padding around the graphic of a BreadCrumbButton
    // (difference between width of a BreadCrumbButton and that of its graphic)
    double constantPadding = Double.NaN;


    int i = 0;
    // right to left
    for (javafx.scene.Node button : asReversed(getChildren())) {
        Node n = (Node) ((TreeItem<?>) button.getUserData()).getValue();
        // when recovering from a selection it's impossible that the node be found,
        // updating the style would cause visible twitching
        if (!options.hasData(SELECTION_RECOVERY)) {
            // set the focus on the one being selected, remove on the others
            // calling requestFocus would switch the focus from eg the treeview to the crumb bar (unusable)
            button.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), newSelection.equals(n));
        }
        // update counters
        totalNumChar += ((Labeled) button).getText().length();
        double childWidth = ((Region) button).getWidth();
        totalChildrenWidth += childWidth;
        totalNumCrumbs++;
        if (Double.isNaN(constantPadding)) {
            Region graphic = (Region) ((Labeled) button).getGraphic();
            if (graphic != null) {
                constantPadding = childWidth - graphic.getWidth();
            }
        }

        if (newSelection.equals(n)) {
            found = true;
            selectedIdx = getChildren().size() - i;
        }

        i++;
    }

    if (!found && !options.hasData(SELECTION_RECOVERY) || options.hasData(SELECTION_RECOVERY) && selectedIdx != 0) {
        // Then we reset the deepest node.

        setDeepestNode(newSelection, getWidthEstimator(totalNumChar, totalChildrenWidth, totalNumCrumbs, constantPadding));
        // set the deepest as focused
        getChildren().get(getChildren().size() - 1)
                     .pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), true);
        selectedIdx = 0;
    } else if (options.hasData(SELECTION_RECOVERY)) {

        Node cur = newSelection;
        // right to left, update underlying nodes without changing display
        // this relies on the fact that selection recovery only selects nodes with exactly the same path
        for (javafx.scene.Node child : asReversed(getChildren())) {
            if (cur == null) {
                break;
            }
            @SuppressWarnings("unchecked")
            TreeItem<Node> userData = (TreeItem<Node>) child.getUserData();
            userData.setValue(cur);
            cur = cur.getParent();
        }
    }
}
 
Example #30
Source File: GridRenderer.java    From chart-fx with Apache License 2.0 4 votes vote down vote up
public GridRenderer() {
    super();

    getStylesheets().add(GridRenderer.CHART_CSS);
    getStyleClass().setAll(GridRenderer.STYLE_CLASS_GRID_RENDERER);
    horMajorGridStyleNode = new Line();
    horMajorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MAJOR_GRID_LINE);
    horMajorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MAJOR_GRID_LINE_H);

    verMajorGridStyleNode = new Line();
    verMajorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MAJOR_GRID_LINE);
    verMajorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MAJOR_GRID_LINE_V);

    horMinorGridStyleNode = new Line();
    horMinorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MINOR_GRID_LINE);
    horMinorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MINOR_GRID_LINE_H);
    horMinorGridStyleNode.setVisible(false);

    verMinorGridStyleNode = new Line();
    verMinorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MINOR_GRID_LINE);
    verMinorGridStyleNode.getStyleClass().add(GridRenderer.STYLE_CLASS_MINOR_GRID_LINE_V);
    verMinorGridStyleNode.setVisible(false);

    drawGridOnTopNode = new Line();
    drawGridOnTopNode.getStyleClass().add(GridRenderer.STYLE_CLASS_GRID_ON_TOP);
    drawGridOnTopNode.getStyleClass().add(GridRenderer.STYLE_CLASS_GRID_ON_TOP);
    drawGridOnTopNode.setVisible(true);

    gridStyleNodes.getChildren().addAll(horMajorGridStyleNode, verMajorGridStyleNode, horMinorGridStyleNode,
            verMinorGridStyleNode, drawGridOnTopNode);

    getChildren().add(gridStyleNodes);
    final Scene scene = new Scene(this);
    scene.getStylesheets().add(GridRenderer.CHART_CSS);
    gridStyleNodes.applyCss();
    final SetChangeListener<? super PseudoClass> listener = evt -> gridStyleNodes.applyCss();
    horMajorGridStyleNode.getPseudoClassStates().addListener(listener);
    verMajorGridStyleNode.getPseudoClassStates().addListener(listener);
    horMinorGridStyleNode.getPseudoClassStates().addListener(listener);
    verMinorGridStyleNode.getPseudoClassStates().addListener(listener);
    drawGridOnTopNode.getPseudoClassStates().addListener(listener);

    ChangeListener<? super Boolean> change = (ob, o, n) -> {
        horMajorGridStyleNode.pseudoClassStateChanged(GridRenderer.SELECTED_PSEUDO_CLASS,
                horMinorGridStyleNode.isVisible());
        verMajorGridStyleNode.pseudoClassStateChanged(GridRenderer.SELECTED_PSEUDO_CLASS,
                verMinorGridStyleNode.isVisible());
        drawGridOnTopNode.pseudoClassStateChanged(GridRenderer.SELECTED_PSEUDO_CLASS,
                drawGridOnTopNode.isVisible());
    };

    horizontalGridLinesVisibleProperty().addListener(change);
    verticalGridLinesVisibleProperty().addListener(change);
    drawOnTopProperty().addListener(change);
}