Java 类javafx.scene.control.TextFormatter 实例源码

项目:hygene    文件:BookmarkCreateController.java   
@Override
public void initialize(final URL location, final ResourceBundle resources) {
    final ObjectProperty<GfaNode> selectedNodeProperty = graphVisualizer.getSelectedSegmentProperty();

    selectedNodeProperty.addListener((observable, oldValue, newValue) ->
            nodePosition.setText(newValue == null ? "" : String.valueOf(newValue.getSegmentIds())));
    radius.textProperty().bind(graphDimensionsCalculator.getRadiusProperty().asString());

    baseOffset.setTextFormatter(new TextFormatter<>(new IntegerStringConverter()));
    baseOffset.setText(String.valueOf(sequenceVisualizer.getOffsetProperty().get()));
    baseOffset.textProperty().addListener((observable, oldValue, newValue) -> updateBaseOffset(newValue));
    sequenceVisualizer.getOffsetProperty().addListener((observable, oldValue, newValue) ->
            baseOffset.setText(String.valueOf(newValue)));

    saveButton.disableProperty().bind(selectedNodeProperty.isNull());
}
项目:hygene    文件:SequenceController.java   
@Override
public void initialize(final URL location, final ResourceBundle resources) {
    sequenceVisualizer.setCanvas(sequenceCanvas);

    setOffset.setTextFormatter(new TextFormatter<>(new IntegerStringConverter()));
    sequenceVisualizer.getOffsetProperty().addListener((observable, oldValue, newValue) -> {
        setOffset.setText(String.valueOf(newValue));

        sequenceTextArea.positionCaret(newValue.intValue());
        sequenceTextArea.selectPositionCaret(newValue.intValue() + 1);
    });

    graphVisualizer.getSelectedSegmentProperty()
            .addListener((observable, oldNode, newNode) -> updateFields(newNode));
    sequenceCanvas.widthProperty().bind(sequenceGrid.widthProperty().subtract(CANVAS_PADDING * 2));

    sequenceViewPane.visibleProperty().bind(sequenceVisualizer.getVisibleProperty()
            .and(graphStore.getGfaFileProperty().isNotNull()));
    sequenceViewPane.managedProperty().bind(sequenceVisualizer.getVisibleProperty()
            .and(graphStore.getGfaFileProperty().isNotNull()));
}
项目:mokka7    文件:ChartViewPresenter.java   
private static void addNumericValidation(TextField field) {
    field.getProperties().put("vkType", "numeric");
    field.setTextFormatter(new TextFormatter<>(c -> {
        if (c.isContentChange()) {
            if (c.getControlNewText().length() == 0) {
                return c;
            }
            try {
                Integer.parseInt(c.getControlNewText());
                return c;
            } catch (NumberFormatException e) {
            }
            return null;

        }
        return c;
    }));
}
项目:mokka7    文件:ReadViewPresenter.java   
private static void addNumericValidation(TextField field) {
    field.getProperties().put("vkType", "numeric");
    field.setTextFormatter(new TextFormatter<>(c -> {
        if (c.isContentChange()) {
            if (c.getControlNewText().length() == 0) {
                return c;
            }
            try {
                Integer.parseInt(c.getControlNewText());
                return c;
            } catch (NumberFormatException e) {
            }
            return null;

        }
        return c;
    }));
}
项目:shuffleboard    文件:AbstractNumberField.java   
protected AbstractNumberField() {
  super();
  setText("0");
  setNumber(getNumberFromText("0"));
  setTextFormatter(new TextFormatter<>(change -> {
    String text = change.getControlNewText();
    if (isStartOfNumber(text)) {
      return change;
    }
    return null;
  }));
  PropertyUtils.bindBidirectionalWithConverter(
      textProperty(),
      number,
      text -> isCompleteNumber(text) ? getNumberFromText(text) : getNumber(),
      num -> Objects.equals(num, getNumberFromText(getText())) ? getText() : num.toString());
}
项目:boutique-de-jus    文件:SpinnerUtil.java   
public  static void initializeSpinner(final Spinner<Integer> spinner, final int minValue, final int maxValue, final int initialValue) {
    spinner.getEditor().setOnKeyPressed(event -> {
        switch (event.getCode()) {
            case UP:
                spinner.increment(1);
                break;
            case DOWN:
                spinner.decrement(1);
                break;
        }
    });
    spinner.setOnScroll(e -> {
        spinner.increment((int) (e.getDeltaY() / e.getMultiplierY()));
    });

    SpinnerValueFactory<Integer> factory = new SpinnerValueFactory.IntegerSpinnerValueFactory(minValue, maxValue, initialValue);
    spinner.setValueFactory(factory);
    spinner.setEditable(true);

    TextFormatter<Integer> formatter = new TextFormatter<>(factory.getConverter(), factory.getValue());
    spinner.getEditor().setTextFormatter(formatter);
    factory.valueProperty().bindBidirectional(formatter.valueProperty());

}
项目:vars-annotation    文件:SharktopodaSettingsPaneController.java   
@FXML
void initialize() {

    UnaryOperator<TextFormatter.Change> filter = change -> {
        String text = change.getText();
        if (text.matches("[0-9]*")) {
            return change;
        }
        return null;
    };

    TextFormatter<String> textFormatter1 = new TextFormatter<>(filter);
    TextFormatter<String> textFormatter2 = new TextFormatter<>(filter);
    controlPortTextField.setTextFormatter(textFormatter1);
    framegrabPortTextField.setTextFormatter(textFormatter2);

    load();
}
项目:vars-annotation    文件:MediaParamsPaneController.java   
@FXML
void initialize() {

    UnaryOperator<TextFormatter.Change> filter = change -> {
        String text = change.getText();
        if (text.matches("[0-9]*")) {
            return change;
        }
        return null;
    };

    TextFormatter<String> textFormatter1 = new TextFormatter<>(filter);
    sequenceNumberTextField.setTextFormatter(textFormatter1);

    cameraIdComboBox.setEditable(true);
}
项目:photometric-data-retriever    文件:DecimalTextField.java   
public DecimalTextField(@NamedArg("formatPattern") String formatPattern, @NamedArg("locale") Locale locale) {
    format = new DecimalFormat(formatPattern, new DecimalFormatSymbols(locale));
    DecimalFilter filter = new DecimalFilter(format);
    super.setTextFormatter(new TextFormatter<>(filter));
    new DecimalFilter().getFormat().getDecimalFormatSymbols().getDecimalSeparator();
    textProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue.endsWith(String.valueOf(filter.getFormat().getDecimalFormatSymbols().getDecimalSeparator()))) {
            newValue = newValue.substring(0, newValue.length() - 1);
        }
        if (newValue.isEmpty()) {
            newValue = "0";
        }
        try {
            value.setValue(format.parse(newValue));
        } catch (ParseException e) {
            value.setValue(0);
        }
    });
}
项目:photometric-data-retriever    文件:TitledTextFieldBox.java   
public void setTextFormatter(TextFormatter<?> value) {
    if (value == null) {
        throw new IllegalArgumentException("TextFormatter value cannot be null.");
    }
    filter = value.getFilter();
    innerTextField.setTextFormatter(new TextFormatter<>(change -> {
        if (useAutoTitles && titleLabel.getText().isEmpty()) {
            if (change.getText().equals(delimiter)) {
                for (Map.Entry<String, String> entry : autoTitles.entrySet()) {
                    if (change.getControlNewText().startsWith(entry.getKey())) {
                        TitledTextFieldBox.this.setTitle(entry.getValue());
                        innerTextField.setText("");
                        return null;
                    }
                }
            }
        }
        return filter.apply(change);
    }));
}
项目:photometric-data-retriever    文件:CoordsFilter.java   
@Override
public TextFormatter.Change apply(TextFormatter.Change change) {
    if (change.getControlNewText().isEmpty()) {
        return change;
    }
    String text = change.getControlNewText();
    String[] split = text.split(" ");
    if (split.length == 2 && change.getText().equals(" ")) {
        return null;
    }
    if (Arrays.stream(split).allMatch(s -> {
        if (s.startsWith("+")) {
            s = s.substring(1);
            if (s.isEmpty()) return true;
        }
        ParsePosition parsePosition = new ParsePosition(0);
        Object object = format.parse(s, parsePosition);

        return (!(object == null || parsePosition.getIndex() < s.length()));
    })) {
        return change;
    }
    return null;
}
项目:myWMS    文件:StockUnitsPlugin.java   
private void changeAmount(Object source, Flow flow, ViewContext context, TableKey key) {
    final long id = key.get("id");

    TextFormatter<BigDecimal> amount = new TextFormatter<>(new BigDecimalConverter());
    TextFormatter<BigDecimal> amountReserved = new TextFormatter<>(new BigDecimalConverter());
    TextField comment = new TextField();

    boolean ok = MDialogs.create(context.getRootNode(), "Transfer Stock Unit")
        .input("Amount", Filters.of(amount,8))  
        .input("Reserved", Filters.of(amountReserved,8))    
        .input("Comment", comment)  
        .showOkCancel();

    if (!ok) return;
    BigDecimal amountVal = amount.getValue();
    BigDecimal resVal = amountReserved.getValue();
    String commentVal = comment.getText();

    StockUnitCRUDRemote suCrud = context.getBean(StockUnitCRUDRemote.class);
    ManageInventoryFacade manageInventory = context.getBean(ManageInventoryFacade.class);
    context.getExecutor().call(() -> {
        StockUnit su = suCrud.retrieve(id);
        manageInventory.changeAmount(new StockUnitTO(su), amountVal, resVal, commentVal);
        return null;
    });
}
项目:urmusic-desktop    文件:NumberTextField.java   
public NumberTextField(NumberFormat format, double min, double max) {
    super();

    this.min = min;
    this.max = max;

    this.setTextFormatter(new TextFormatter<>((c) -> {
        if(c.getControlNewText().isEmpty()) return c;

        ParsePosition parsePosition = new ParsePosition(0);
        Number num = format.parse(c.getControlNewText(), parsePosition);

        if(num == null || parsePosition.getIndex() < c.getControlNewText().length() || num.doubleValue() < this.min || num.doubleValue() > this.max) return null;

        return c;
    }));
}
项目:rs-timer    文件:MainWindow.java   
/**
 * Third entry. This if it returns a value actually creates the tab
 */
void showNewTabColumnsDialog(String name, int rows) {
    logger.info("showNewTabColumnsDialog was called with the data: " + name + " & " + rows);
    if (rows > 0) {
        finishNewTabDialogs(rows, 0, name);
        return;
    }
    TextInputDialog inputDialog = new TextInputDialog();
    inputDialog.setContentText("Enter the number of columns to apply to the tab");
    inputDialog.getEditor().setTextFormatter(new TextFormatter<Integer>(new IntegerStringConverter()));
    inputDialog.getEditor().setText("0");
    inputDialog.setHeaderText(null);
    inputDialog.setTitle("New Tab Columns");
    inputDialog.showAndWait()
        .filter(response -> !"".equals(response))
        .ifPresent( response -> this.finishNewTabDialogs(rows, Integer.parseInt(response), name)); 
}
项目:hygene    文件:QuerySettingsController.java   
@Override
public void initialize(final URL location, final ResourceBundle resources) {
    nodeId.setTextFormatter(new TextFormatter<>(new NumberStringConverter()));
    radius.setTextFormatter(new TextFormatter<>(new NumberStringConverter()));

    currentNodeId.textProperty().bind(graphDimensionsCalculator.getCenterNodeIdProperty().asString());
    currentRadius.textProperty().bind(graphDimensionsCalculator.getRadiusProperty().asString());

    graphDimensionsCalculator.getCenterNodeIdProperty().addListener(
            (observable, oldValue, newValue) -> nodeId.setText(String.valueOf(newValue)));
    graphDimensionsCalculator.getRadiusProperty().addListener(
            (observable, oldValue, newValue) -> radius.setText(String.valueOf(newValue)));
}
项目:Hive_Game    文件:NewGameScreenController.java   
@FXML
public void initialize(URL url, ResourceBundle rb) {
    UnaryOperator<TextFormatter.Change> filter = c -> {
        String proposedText = c.getControlNewText();
         if (proposedText.matches(".{0,15}")) {
            return c ;
        } else {
            return null ;
        }
    };
    namePlayer1.setTextFormatter(new TextFormatter<String>(filter));
    namePlayer2.setTextFormatter(new TextFormatter<String>(filter));
}
项目:Hive_Game    文件:NetworkScreenController.java   
/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
           UnaryOperator<TextFormatter.Change> filter = c -> {
               String proposedText = c.getControlNewText();
                if (proposedText.matches(".{0,15}")) {
                   return c ;
               } else {
                   return null ;
               }
           };
           playerName.setTextFormatter(new TextFormatter<String>(filter));   
}
项目:x-facteur    文件:MapView.java   
protected void makeInteractivity() {
    // default field values and format
    postOfficeStreet.setText(PathController.getWalkingPO().getStreet());
    postOfficeCity.setText(PathController.getWalkingPO().getCity());
    maxTime.setTextFormatter(new TextFormatter<Double>(new DoubleStringConverter(), PathController.getMaxTime()));

    // genBtn disabled state
    genBtn.setDisable(postOfficeStreet.getLength() == 0 || postOfficeCity.getLength() == 0 || maxTime.getLength() == 0);
    postOfficeStreet.setOnKeyReleased(e -> {
        genBtn.setDisable(postOfficeStreet.getLength() == 0 || postOfficeCity.getLength() == 0 || maxTime.getLength() == 0);
    });
    postOfficeCity.setOnKeyReleased(e -> {
        genBtn.setDisable(postOfficeStreet.getLength() == 0 || postOfficeCity.getLength() == 0 || maxTime.getLength() == 0);
    });
    maxTime.setOnKeyReleased(e -> {
        genBtn.setDisable(postOfficeStreet.getLength() == 0 || postOfficeCity.getLength() == 0 || maxTime.getLength() == 0);
    });

    // genBtn action
    genBtn.setOnAction(e -> {
        PathController.setPostOffice(new Shipment(postOfficeStreet.getText(), postOfficeCity.getText(), false));
        PathController.setMaxTime(Double.parseDouble(maxTime.getText()));
        PathController.generate();
        PathController.display();
    });

    // wView config
    wView.getEngine().load("https://www.google.fr/maps");
}
项目:infxnity    文件:MaskTextFilterTest.java   
@Override
public void start(final Stage stage) throws Exception
{
    textField = new TextField();
    textField.setId("formatted");

    final MaskCharacter[] mask = MaskBuilder.newBuilder()
                                            .appendLiteral("\\")
                                            .appendDigit()
                                            .appendLiteral(",")
                                            .appendHexa()
                                            .appendLiteral(".")
                                            .appendLetter()
                                            .appendLiteral("$")
                                            .appendLetterOrDigit()
                                            .appendLiteral("!")
                                            .appendLowerCase()
                                            .appendUpperCase()
                                            .appendLiteral("U")
                                            .appendAny()
                                            .appendLiteral("^")
                                            .append(1, //
                                                    c -> (c == '-' || c == '+' || c == 'M' || c == 'P'),
                                                    c -> (c == '+' || c == 'P') ? 'P' : 'M', '_')
                                            .appendLiteral("/")
                                            .build();

    textField.setTextFormatter(new TextFormatter<>(new MaskTextFilter(textField, true, mask)));

    final Scene scene = new Scene(textField, 200, 50);
    stage.setScene(scene);
    stage.show();
}
项目:drd    文件:FormUtils.java   
public static void initTextFormater(TextField textField, MaxActValue maxActValue) {
    textField.setTextFormatter(new TextFormatter<>(new NumberStringConverter()));
    textField.setTextFormatter(new TextFormatter<>(new NumberStringConverter(), null,
        FormUtils.integerFilter(
            maxActValue.getMinValue().intValue(),
            maxActValue.getMaxValue().intValue()
    )));
    textField.textProperty().bindBidirectional(maxActValue.actValueProperty(), new NumberStringConverter());
}
项目:LanternNBT    文件:CharConverter.java   
@Override
protected UnaryOperator<TextFormatter.Change> getFilter() {
    return change -> {
        final String newText = change.getControlNewText();
        return newText.isEmpty() || newText.length() == 1 ? change : null;
    };
}
项目:LanternNBT    文件:AbstractConverter.java   
/**
 * Constructs a new {@link TextFormatter} for this {@link AbstractConverter}.
 *
 * @return The text transformer
 */
public TextFormatter<T> constructFormatter() {
    if (this.cachedFilter == null) {
        this.cachedFilter = getFilter();
    }
    return new TextFormatter<>(this, null, this.cachedFilter);
}
项目:GestureFX    文件:LenaSample.java   
private static TextFormatter<String> createDecimalFormatter() {
    DecimalFormat format = new DecimalFormat("#.0");
    format.setNegativePrefix("-");
    return new TextFormatter<>(c -> {
        if (c.getControlNewText().isEmpty()) return c;
        ParsePosition pos = new ParsePosition(0);
        Number result = format.parse(c.getControlNewText(), pos);
        if (result == null || pos.getIndex() < c.getControlNewText().length()) {
            return null;
        } else return c;
    });
}
项目:photometric-data-retriever    文件:DecimalFilter.java   
@Override
public TextFormatter.Change apply(TextFormatter.Change change) {
    if (change.getControlNewText().isEmpty()) {
        return change;
    }

    ParsePosition parsePosition = new ParsePosition(0);
    Object object = format.parse(change.getControlNewText(), parsePosition);
    if (object == null || parsePosition.getIndex() < change.getControlNewText().length()) {
        return null;
    } else {
        return change;
    }
}
项目:programmierpraktikum-abschlussprojekt-team-1    文件:TextFormatterDemo.java   
@Override
public void start(Stage primaryStage)
{
   Label lblAge = new Label("Age");
   TextField txtAge = new TextField("");
   StringConverter<Integer> formatter;
   formatter = new StringConverter<Integer>()
               {
                  @Override
                  public Integer fromString(String string)
                  {
                     System.out.println("fromString(): string = " + string);
                     return Integer.parseInt(string);
                  }

                  @Override
                  public String toString(Integer object)
                  {
                     System.out.println("toString(): object = " + object);
                     if (object == null)
                        return "0";
                     System.out.println("object.tostring = " + 
                                        object.toString());
                     return object.toString();
                  }
               };
   txtAge.setTextFormatter(new TextFormatter<Integer>(formatter));
   HBox hboxForm = new HBox(10);
   hboxForm.setPadding(new Insets(10, 10, 10, 10));
   hboxForm.getChildren().addAll(lblAge, txtAge);
   Scene scene = new Scene(hboxForm);
   primaryStage.setScene(scene);
   primaryStage.setResizable(false);
   primaryStage.setTitle("TextFormatterDemo");
   primaryStage.show();
}
项目:myWMS    文件:TreatOrderController.java   
public void assignPartialStockUnits(Event e) {
    MDialogs.showFormattedInput(getView(), "Maximum pick amount", "Max Pick Qty", 
            new TextFormatter<BigDecimal>(new BigDecimalConverter(), lastMax, Filters.numeric()))
    .filter(max -> max.compareTo(BigDecimal.ZERO) > 0)
    .ifPresent(max -> {
        lastMax = max;
        assignStockUnits(e, max);
    });
}
项目:factoryfx    文件:TypedTextFieldHelper.java   
private static void setupTextField(TextField textField, Consumer<String> converter) {
    textField.setTextFormatter(new TextFormatter<>(change -> {
        try {
            if (!Strings.isNullOrEmpty(change.getControlNewText())) {
               converter.accept(change.getControlNewText());
            }
            return change;
        } catch (Exception e) {
            return null;
        }
    }));
}
项目:trex-stateless-gui    文件:MacProtocolView.java   
/**
 * Add Mac input field validations
 */
@Override
protected void addInputValidation() {
    final UnaryOperator<TextFormatter.Change> ipAddressFilter = Util.getTextChangeFormatter(validateAddressRegex());
    srcAddress.setTextFormatter(new TextFormatter<>(ipAddressFilter));
    dstAddress.setTextFormatter(new TextFormatter<>(ipAddressFilter));

    // add format for step and count
    srcCount.setTextFormatter(Util.getNumberFilter(4));
    dstCount.setTextFormatter(Util.getNumberFilter(4));
    srcStep.setTextFormatter(Util.getNumberFilter(3));
    dstStep.setTextFormatter(Util.getNumberFilter(3));
}
项目:trex-stateless-gui    文件:ImportedPacketPropertiesView.java   
/**
 * Add input formatter instructions
 */
private void addInputValidation() {
    UnaryOperator<TextFormatter.Change> unitFormatter = Util.getTextChangeFormatter(Util.getUnitRegex(false));
    srcCountTF.setTextFormatter(new TextFormatter<>(unitFormatter));
    dstCountTF.setTextFormatter(new TextFormatter<>(unitFormatter));

    countTF.setTextFormatter(Util.getNumberFilter(5));

    UnaryOperator<TextFormatter.Change> digitsFormatter = Util.getTextChangeFormatter(digitsRegex());
    speedupTF.setTextFormatter(new TextFormatter<>(digitsFormatter));
    ipgTF.setTextFormatter(new TextFormatter<>(digitsFormatter));

}
项目:trex-stateless-gui    文件:MultiplierOption.java   
/**
 * Build multiplier view UI
 *
 * @param title
 * @param group
 */
private void buildUI(String title, ToggleGroup group) {
    // add radio button
    selection = new RadioButton(title);
    selection.setToggleGroup(group);
    selection.selectedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
        if (newValue) {
            multiplierSelectionEvent.onMultiplierSelect(type);
        }
        value.setDisable(!newValue);
    });
    setTooltip();
    getChildren().add(selection);
    MultiplierOption.setTopAnchor(selection, 15d);
    MultiplierOption.setLeftAnchor(selection, 0d);

    // text field
    value = new TextField();
    value.setPrefSize(120, 22);
    value.setDisable(true);
    value.addEventFilter(KeyEvent.KEY_RELEASED, multiplierSelectionEvent.validateInput());

    String regex = unitRegex();
    final UnaryOperator<TextFormatter.Change> keyPressFilter = c -> {
        String text = c.getControlNewText();
        if (text.matches(regex)) {
            return c;
        } else {
            return null;
        }
    };
    value.setTextFormatter(new TextFormatter<>(keyPressFilter));

    getChildren().add(value);
    MultiplierOption.setTopAnchor(value, 43d);
    MultiplierOption.setLeftAnchor(value, 0d);
    MultiplierOption.setBottomAnchor(value, 15d);
}
项目:trex-stateless-gui    文件:Util.java   
/**
 * Return textChange formatter
 *
 * @param regex
 * @return
 */
public static UnaryOperator<TextFormatter.Change> getTextChangeFormatter(String regex) {
    return c -> {
        String text = c.getControlNewText();
        if (text.matches(regex)) {
            return c;
        } else {
            return null;
        }
    };
}
项目:BudgetMaster    文件:ColorPickController.java   
private void initializeTextField(Slider slider, TextField textField)
{
    textField.setTextFormatter(new TextFormatter<>(c -> {
        if(c.getControlNewText().isEmpty())
        {
            return c;
        }

        if(c.getControlNewText().matches("[0-9]*"))
        {
            if(Double.parseDouble(c.getControlNewText()) > 255)
            {
                return null;
            }
            else
            {
                return c;
            }               
        }
        else
        {
            return null;
        }
    }));        

    textField.textProperty().addListener((observer, oldValue, newValue)->{
        double value;
        if(newValue.isEmpty())
        {
            value = 0;
        }
        else
        {
            value = Double.parseDouble(newValue);
        }
        slider.setValue(value);             
        textFieldHex.setText(ConvertTo.toRGBHexWithoutOpacity(getColor()));
    });
}
项目:Kruispunt-Simulatie    文件:Kruispunt_Sim.java   
@Deprecated
public static void addTextLimiter(final TextField tf, final int maxLength) {
    TextFormatter<String> formatter = new TextFormatter<>(change -> {
        String text = change.getText();
        text = text.replaceAll("[^0-9]", "");
        if (tf.getText().length() > maxLength - 1) {
            text = "";
        }
        change.setText(text);
        return change;
    });

    tf.setTextFormatter(formatter);
}
项目:iso-game-engine    文件:TypedTextField.java   
public TypedTextField() {
    super();

    this.setTextFormatter(new TextFormatter<>(change -> {
        if ((change.isAdded() || change.isReplaced())
            && !parseValue(change.getText()).isPresent()
        ) {
            change.setText("");
        }
        return change;
    }));
}
项目:StreamSis    文件:IntegerTextField.java   
/**
 * Modify TextField so only integer numbers will be allowed to be input in it.
 *
 * @param maxAllowedValue
 *            The maximum allowed value to input. If input value is more than that, the input
 *            will not occur.
 * @param allowNegativeValues
 *            Allow negative values or not.
 */
private void setIntegerFilter(int maxAllowedValue, boolean allowNegativeValues) {
    this.setTextFormatter(new TextFormatter<>(c -> {
        String regex = "\\d*";
        if (allowNegativeValues) {
            if (c.getControlNewText().equals("-"))
                return c;
            regex = "-?\\d*";
        }
        if (c.getControlNewText().isEmpty())
            return c;
        if (c.getControlNewText().startsWith("0")) {
            if (c.getControlNewText().length() > 1) {
                return null;
            }
        }
        if (c.getControlNewText().matches(regex)) {
            int parsedInt;
            try {
                parsedInt = Integer.parseInt(c.getControlNewText());
            } catch (NumberFormatException ex) {
                return null;
            }
            if (parsedInt > maxAllowedValue)
                return null;
            if (!allowNegativeValues) {
                if (parsedInt < 0)
                    return null;
            }
            return c;
        }
        return null;
    }));
}
项目:StreamSis    文件:DoubleTextField.java   
/**
 * Modify TextField so only double/integer numbers will be allowed to be input in it.
 *
 * @param maxAllowedValue
 *            The maximum allowed value to input. If input value is more than that, the input
 *            will not occur.
 * @param allowNegativeValues
 *            Allow negative values or not.
 */
private void setDoubleFilter(double maxAllowedValue, boolean allowNegativeValues) {
    DecimalFormat format = new DecimalFormat();
    this.setTextFormatter(new TextFormatter<>(c -> {
        String newText = c.getControlNewText();
        if (newText.isEmpty())
            return c;
        // The user might start typing the number with minus sign, though it could not be 
        if (allowNegativeValues) {
            if (newText.equals("-"))
                return c;
        }
        ParsePosition parsePosition = new ParsePosition(0);
        Number number = format.parse(newText, parsePosition);
        if (number == null) // Means unable to parse
            return null;
        if (parsePosition.getIndex() < newText.length()) // Means extra symbols exist
            return null;
        double numberConvertedToDouble = number.doubleValue();
        if (numberConvertedToDouble > maxAllowedValue)
            return null;
        if (!allowNegativeValues) {
            if (numberConvertedToDouble < 0)
                return null;
        }
        return c;
    }));
}
项目:StreamSis    文件:CommonElementFieldsController.java   
/**
 * Replaces {@link #nameTextField} responsible for editing name with new one. <br>
 * It's needed because when we do {@link #recreateValidationSupport()}, the old
 * ValidationSupport object still have registered validator to nameTextField. So to garbage
 * collect old ValidationSupport object also we have to dump nameTextField with it.
 */
private void recreateNameTextField() {
    TextField newTextField = new TextField();
    newTextField.setMaxWidth(250.0);
    newTextField.setPrefWidth(250.0);
    GUIUtil.replaceChildInPane(nameTextField, newTextField);
    nameTextField = newTextField;
    nameTextField.setDisable(!inputAllowed);
    // Let's not allow very long names
    UnaryOperator<Change> filter = c -> {
        if (c.getControlNewText().length() > 35) {
            logger.debug("The CuteElement's name is too long to pass the input filter.");
            return null;
        }
        return c;
    };
    nameTextField.setTextFormatter(new TextFormatter<>(filter));
    // Reset nameTextField on ESC key
    nameTextField.setOnKeyReleased(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent t) {
            if (t.getCode() == KeyCode.ESCAPE) {
                nameTextField.setText(originalName);
                // When root's parent is focused, second hit to Escape key will close panel
                root.getParent().requestFocus();
            }
        }
    });
}
项目:subshare    文件:LocalRepoPane.java   
public LocalRepoPane(final LocalRepo localRepo) {
    this.localRepo = assertNotNull(localRepo, "localRepo");
    this.repoSyncDaemon = RepoSyncDaemonLs.getRepoSyncDaemon();
    this.repoSyncTimer = RepoSyncTimerLs.getRepoSyncTimer();
    loadDynamicComponentFxml(LocalRepoPane.class, this);
    nameTextField.setTextFormatter(new TextFormatter<String>(new UnaryOperator<Change>() {
        @Override
        public Change apply(Change change) {
            String text = change.getText();
            if (text.startsWith("_") && change.getRangeStart() == 0)
                return null;

            if (text.indexOf('/') >= 0)
                return null;

            return change;
        }
    }));
    bind();
    updateActivities();
    updateState();
    updateNextSync();
    updateSyncPeriodUi();

    final EventHandler<? super MouseEvent> syncStateMouseEventFilter = event -> showSyncStateDialog();
    syncStateStartedFinishedTextField.addEventFilter(MouseEvent.MOUSE_CLICKED, syncStateMouseEventFilter);
    syncStateSeverityLabel.addEventFilter(MouseEvent.MOUSE_CLICKED, syncStateMouseEventFilter);

    historyPaneSupport = new HistoryPaneSupport(this);

    tabPane.getSelectionModel().selectedItemProperty().addListener((InvalidationListener) observable -> createOrForgetUserRepoKeyListPane());
    createOrForgetUserRepoKeyListPane();
}
项目:subshare    文件:ValidityPane.java   
public ValidityPane(final CreatePgpKeyParam createPgpKeyParam) {
    this.createPgpKeyParam = assertNotNull(createPgpKeyParam, "createPgpKeyParam"); //$NON-NLS-1$
    loadDynamicComponentFxml(ValidityPane.class, this);

    validityNumberSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, Integer.MAX_VALUE));
    validityNumberSpinner.valueProperty().addListener((InvalidationListener) observable -> {
        updateValiditySeconds();
        updateComplete();
    });
    validityNumberSpinner.getEditor().setTextFormatter(new TextFormatter<String>(new UnaryOperator<Change>() {
        @Override
        public Change apply(Change change) {
            final String text = change.getControlNewText();
            // We cannot accept an empty String, because the IntegerValueFactory runs into an NPE, then :-(
            try {
                Integer.parseInt(text);
            } catch (NumberFormatException x) {
                return null;
            }
            return change;
        }
    }));

    validityTimeUnitComboBox.setItems(FXCollections.observableArrayList(TimeUnit.YEAR, TimeUnit.MONTH, TimeUnit.DAY));
    validityTimeUnitComboBox.setConverter(timeUnitStringConverter);
    validityTimeUnitComboBox.getSelectionModel().clearAndSelect(0);
    validityTimeUnitComboBox.valueProperty().addListener((InvalidationListener) observable -> updateValiditySeconds());

    createPgpKeyParam.addPropertyChangeListener(CreatePgpKeyParam.PropertyEnum.validitySeconds, validitySecondsPropertyChangeListener);
    updateValidityNumberSpinner();

    updateComplete();
}
项目:rs-timer    文件:MainWindow.java   
/**
 * Second entry. This if it returns a value forwards to the third entry.
 */
void showNewTabRowsDialog(String name) {
    logger.info("showNewTabRowsDialog Was called with the string: " + name);
    TextInputDialog inputDialog = new TextInputDialog();
    inputDialog.getEditor().setTextFormatter(new TextFormatter<Integer>(new IntegerStringConverter()));
    inputDialog.setContentText("Enter the number of rows, or 0 to choose columns instead");
    inputDialog.getEditor().setText("0");
    inputDialog.setHeaderText(null);
    inputDialog.setTitle("New Tab Rows");
    inputDialog.showAndWait()
        .filter(response -> !"".equals(response))
        .ifPresent( response -> showNewTabColumnsDialog(name, Integer.parseInt(response))); //NOSONAR
}