logo
Tags down

shadow

Using TextFormatter Property


By : Ferdinand
Date : September 17 2020, 10:00 PM
will help you TornadoFX actually has a filter builder that incorporates a text formatter:
code :
override val root = vbox {
    textfield(model.instrument) { 
        filterInput { change ->
            change.text = change.text.toUpperCase()
            true
        }
    }
}


Share : facebook icon twitter icon

EnterpriseLibrary CustomTraceListener not respecting TextFormatter


By : uridabash
Date : March 29 2020, 07:55 AM
may help you . Chris Tavares is correct. The solution is as follows:
Override the TraceData() method, obtain an instance of the formatter call formatter.Format, pass it to WriteLine()
code :
namespace Sample1
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Cognoware.Collections.Generic;
    using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
    using System.Diagnostics;
    using Microsoft.Practices.EnterpriseLibrary.Logging;

    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class CircularTraceListener: CustomTraceListener
    {
        private string tmp = String.Empty;
        public override void Write(string message)
        {
            tmp += message;
        }

        public override void WriteLine(string message)
        {
            tmp += message;
        }

        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
            if ((this.Filter == null) || this.Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null))
            {
                if (data is LogEntry)
                {
                    if (this.Formatter != null)
                    {
                        WriteLine(this.Formatter.Format(data as LogEntry));
                    }
                    else
                    {
                        base.TraceData(eventCache, source, eventType, id, data);
                    }
                }
                else
                {
                    base.TraceData(eventCache, source, eventType, id, data);
                }
            }
        }
    }
}

Indentation of second line in WPF TextFormatter


By : boyband6666
Date : March 29 2020, 07:55 AM
With these it helps This is far from being easy. I suggest you use WPF's Advanced Text Formatting.
There is an offical (relatively poor, but it's the only one) sample: TextFormatting.
code :
<Window x:Class="WpfApp3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1"
        Title="MainWindow" Height="550" Width="725">
    <StackPanel Margin="10">
        <TextBox  Name="TbSource" AcceptsReturn="True" TextWrapping="Wrap" BorderThickness="1"
                 VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"></TextBox>
        <Border BorderThickness="1" BorderBrush="#ABADB3" Margin="0" Padding="0">
            <local:MyTextControl Margin="5" Text="{Binding ElementName=TbSource, Path=Text}" />
        </Border>
    </StackPanel>
</Window>
[ContentProperty(nameof(Text))]
public class MyTextControl : FrameworkElement
{
    // I have only declared Text as a dependency property, but fonts, etc should be here
    public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyTextControl),
        new FrameworkPropertyMetadata(string.Empty,
            FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));

    private List<TextLine> _lines = new List<TextLine>();
    private TextFormatter _formatter = TextFormatter.Create();

    public string Text { get => ((string)GetValue(TextProperty)); set { SetValue(TextProperty, value); } }

    protected override Size MeasureOverride(Size availableSize)
    {
        // dispose old stuff
        _lines.ForEach(l => l.Dispose());

        _lines.Clear();
        double height = 0;
        double width = 0;
        var ts = new MyTextSource(Text);
        var index = 0;
        double maxWidth = availableSize.Width;
        if (double.IsInfinity(maxWidth))
        {
            // it means width was not fixed by any constraint above this.
            // we pick an arbitrary value, we could use visual parent, etc.
            maxWidth = 100;
        }

        double firstWordWidth = 0; // will be computed with the 1st line

        while (index < Text.Length)
        {
            // we indent the second line
            var props = new MyTextParagraphProperties(new MyTextRunProperties(), _lines.Count == 1 ? firstWordWidth : 0);
            var line = _formatter.FormatLine(ts, index, maxWidth, props, null);
            if (_lines.Count == 0)
            {
                // get first word and whitespace real width (so we can support justification / whitespaces widening, kerning)
                firstWordWidth = line.GetDistanceFromCharacterHit(new CharacterHit(ts.FirstWordAndSpaces.Length, 0));
            }

            index += line.Length;
            _lines.Add(line);

            height += line.TextHeight;
            width = Math.Max(width, line.WidthIncludingTrailingWhitespace);
        }
        return new Size(width, height);
    }

    protected override void OnRender(DrawingContext dc)
    {
        double height = 0;
        for (int i = 0; i < _lines.Count; i++)
        {
            if (i == _lines.Count - 1)
            {
                // last line centered (using pixels, not characters)
                _lines[i].Draw(dc, new Point((RenderSize.Width - _lines[i].Width) / 2, height), InvertAxes.None);
            }
            else
            {
                _lines[i].Draw(dc, new Point(0, height), InvertAxes.None);
            }
            height += _lines[i].TextHeight;
        }
    }
}

// this is a simple text source, it just gives back one set of characters for the whole string
public class MyTextSource : TextSource
{
    public MyTextSource(string text)
    {
        Text = text;
    }

    public string Text { get; }

    public string FirstWordAndSpaces
    {
        get
        {
            if (Text == null)
                return null;

            int pos = Text.IndexOf(' ');
            if (pos < 0)
                return Text;

            while (pos < Text.Length && Text[pos] == ' ')
            {
                pos++;
            }

            return Text.Substring(0, pos);
        }
    }

    public override TextRun GetTextRun(int index)
    {
        if (Text == null || index >= Text.Length)
            return new TextEndOfParagraph(1);

        return new TextCharacters(
           Text,
           index,
           Text.Length - index,
           new MyTextRunProperties());
    }

    public override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int indexLimit) => throw new NotImplementedException();
    public override int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int index) => throw new NotImplementedException();
}

public class MyTextParagraphProperties : TextParagraphProperties
{
    public MyTextParagraphProperties(TextRunProperties defaultTextRunProperties, double indent)
    {
        DefaultTextRunProperties = defaultTextRunProperties;
        Indent = indent;
    }

    // TODO: some of these should be DependencyProperties on the control
    public override FlowDirection FlowDirection => FlowDirection.LeftToRight;
    public override TextAlignment TextAlignment => TextAlignment.Justify;
    public override double LineHeight => 0;
    public override bool FirstLineInParagraph => true;
    public override TextRunProperties DefaultTextRunProperties { get; }
    public override TextWrapping TextWrapping => TextWrapping.Wrap;
    public override TextMarkerProperties TextMarkerProperties => null;
    public override double Indent { get; }
}

public class MyTextRunProperties : TextRunProperties
{
    // TODO: some of these should be DependencyProperties on the control
    public override Typeface Typeface => new Typeface("Segoe UI");
    public override double FontRenderingEmSize => 20;
    public override Brush ForegroundBrush => Brushes.Black;
    public override Brush BackgroundBrush => Brushes.White;
    public override double FontHintingEmSize => FontRenderingEmSize;
    public override TextDecorationCollection TextDecorations => new TextDecorationCollection();
    public override CultureInfo CultureInfo => CultureInfo.CurrentCulture;
    public override TextEffectCollection TextEffects => new TextEffectCollection();
}

How to add TextField with TextFormatter and Listener into TableCell?


By : Cheicky DaniJo Sanic
Date : March 29 2020, 07:55 AM
With these it helps Actually you can handle both conversion and preventing invalid input using a TextFormatter using a StringConverter and a UnaryOperator. The following code assumes you've got a ObjectProperty in your Water class and the amountProperty() method returns it.
If the Water.toString(int) or Water.toString(Integer) method does not exist, you need to implement the conversion from int to string for the following code to work.
code :
private static final StringConverter<Integer> VALUE_CONVERTER = new StringConverter<Integer>() {

    @Override
    public String toString(Integer object) {
        return object == null ? Water.getAreaFormat() : Water.toString(object);
    }

    @Override
    public Integer fromString(String string) {
        return Water.toInt(string);
    }

};

// filter copied unmodified from your code
private static final UnaryOperator<TextFormatter.Change> VALUE_FILTER = change -> {
    int maxLength = 10;

    if (change.isAdded()) {
        if(change.getControlNewText().length() <= maxLength){
            if (change.getText().contains(",")) {
                change.setText(change.getText().replaceAll(",", "."));
            }
            change = change.getControlNewText().matches("^\\d*(\\.\\d{0,1})?$") ? change : null;
        } else {
            if (change.getText().length() == 1){
                change = null;
            } else {
                int allowedLength = maxLength - change.getControlText().length();
                change.setText(change.getText().substring(0, allowedLength));
            }
        }
    }
    return change;
};

@FXML
private TableColumn<Water, Integer> valueColumn;

@FXML
private void initialize(){
    waterTable.setItems(FXCollections.observableArrayList(thisMonthWaterList));

    valueColumn.setCellValueFactory(cellData -> cellData.getValue().amountProperty());
    valueColumn.setCellFactory(new Callback<TableColumn<Water, Integer>, TableCell<Water, Integer>>() {

        @Override
        public TableCell<Water, Integer> call(TableColumn<Water, Integer> param) {
            return new TableCell<Water, Integer>() {

                private final TextFormatter<Integer> formatter;
                private final TextField textField;

                {
                    textField = new TextField();
                    formatter = new TextFormatter<>(VALUE_CONVERTER, null, VALUE_FILTER);
                    textField.setTextFormatter(formatter);
                    formatter.valueProperty().addListener((o, oldValue, newValue) -> {
                        Water water = (Water) getTableRow().getItem();
                        if (!Objects.equals(water.getAmount(), newValue)) {
                             // update item and db, if value was modified
                             water.setAmount(newValue);
                             WaterDA.update(water);
                        }
                    });
                }

                @Override
                protected void updateItem(Integer value, boolean empty){
                    super.updateItem(value, empty);
                    if (empty){
                        setGraphic(null);
                    } else {
                        setGraphic(textField);
                        formatter.setValue(value);
                    }
                }
            };
        }
    });

}

Full justify of last line in WPF TextFormatter


By : Dr.JimDPhD
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further In your TextSource implementation, in GetTextRun function, at the end of each paragraph return an TextEmbeddedObject object with very wide width, and with height 0.
This way you will force the last line to be justified.
code :
class MyTextEmbeddedObject : TextEmbeddedObject
{
    public override LineBreakCondition BreakBefore => LineBreakCondition.BreakAlways;

    public override LineBreakCondition BreakAfter => LineBreakCondition.BreakRestrained;

    public override bool HasFixedSize => true;

    public override CharacterBufferReference CharacterBufferReference => throw new NotImplementedException();

    public override int Length => 1;

    public override TextRunProperties Properties => GenericTextParagraphProperties._defaultTextRunProperties;

    public override Rect ComputeBoundingBox(bool rightToLeft, bool sideways)
    {
        throw new NotImplementedException();
    }

    public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways)
    {
        throw new NotImplementedException();
    }

    public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth)
    {
        return new TextEmbeddedObjectMetrics(10000 /* very wide width */, 0, 0);
    }
}

Javafx TextFormatter Backspacing issue


By : akash
Date : March 29 2020, 07:55 AM
I hope this helps you . From the documentation of TextFormatter.getFilter():
code :
return new TextFormatter<Number>(
    new NumberStringConverter(CURRENCY_DECIMAL_FORMAT));
Related Posts Related Posts :
  • Kotlin, unresolved reference on everything in VSCode
  • brief function code for null check in kotlin
  • How to capture an argument that was passed to a mocked function and return it?
  • Issue when trying to import Jacoco code coverage to SonarQube: Cannot import coverage information for file, coverage dat
  • Proposed change of `equals` to `==` can't be applied to Char and String?
  • How to use kotlin's default parameter only if the input is not null?
  • Please Explain to me this kotlin statement?
  • How to check if a string is a valid email in android?
  • This annotation is not applicable to target member property without backing field or delegate
  • How to split on unicode whitespace in kotlin
  • How can Kotlin's Set be covariant when contains() takes E?
  • Kotlin inline class in JUnit tests
  • Lambda as a function parameter -> accept methods only from particular class
  • Kotlin - How do I concatenate a String to an Int value?
  • Why I Cannot Access to this function?
  • Kotlin test, how to run BeforeEach with DescribeSpec test style
  • Convince Kotlin compiler map has a key
  • how do you declare static property in kotlin?
  • How can i call an interface in kotlin?
  • Check if any array item is not empty
  • kotlin, where the return from inside the let go
  • Kotlin: Should mutableList be declared as Val or Var?
  • Convert Long to String in Kotlin
  • Extension property inside class: Unresolved reference: errorResponse
  • How to extend enums in Kotlin?
  • Idiomatic way in kotlin to transform/append to a list?
  • How to avoid nest 「null check」by "?.let"?
  • How to simply add another source to MediatorLiveData in kotlin?
  • Convert Set<Int> to varargs efficiently in Kotlin
  • Getting an error Using 'body(): ResponseBody?' is an error. moved to val with okhttp
  • Kotlin String to Int or zero (default value)
  • Return value only of the faster coroutine
  • Is there a Kotlin Coroutines Channel equivalent of RxJava's onDispose?
  • Create fat jar from kotlin multiplatform project
  • Short circuiting operation in Kotlin sequences
  • How to output deprecation warnings for Kotlin code?
  • Why does generated getter method have dollar signs in it?
  • For a final class why does when complain?
  • Reference value of constant with KDoc
  • How to create this coroutines in kotlin?
  • OkHttp: NoSuchMethodError copyInto in TlsUtil
  • Why do unreachable statements method not result in a compilation error?
  • Static/Const map key check at compile time
  • Escaping double quotes inside backticks
  • Does Kotlin have primitive types?
  • What is exactly null in kotlin and why i can't cause NPE with it?
  • Why would you use a Kotlin companion object rather than an initializer block for creation?
  • how to use operator overloading in Kotlin to divide a number by a numeric vector
  • How to use get() with backing fields in kotlin
  • How to map string to function and call it later
  • Kotlin enum constructor argument 'must be initialized' with companion object constant without qualifier name
  • Please explain to me class delegation in Kotlin
  • Error:(1, 41) Kotlin: Symbol is declared in module 'jdk.internal.opt' which does not export package 'jdk.i
  • How to properly make blocking service calls with Kotlin coroutines?
  • Gson SerializedName in a Kotlin interface
  • Kotlin convert FileTime to day, month, year
  • Kotlin how to move a file to a other directory?
  • If first param is true, then must pass second param in function
  • MutableLiveData for collections
  • How to replace long chain of forEach{} statements in Kotlin?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk