How to set the letter spacing (aka tracking) of a

2019-09-05 00:58发布

问题:

The internet teaches me it was available in JavaFX 1.x (most examples I found, were in the .fx format, which is now obsolete). But it now (JavaFX 2.*) seems impossible to do. I can think of one way for accomplishing the effect I want: stuff every letter in a Text and add all of them to a FlowPane with the HGap set to the wanted spacing. But I'd rather use this as a last resort. Oh, I've also tried putting -fx-letter-spacing in my stylesheet, didn't work either.

回答1:

I made a custom class that fits my needs (warning: doesn't have a lot of functionality)

public class LetterSpacedText extends FlowPane {
    private Font font;
    private Color fill;

    public LetterSpacedText(String s, double spacing) {
        setText(s);
        setHgap(spacing);
    }

    public void setText(String s) {
        getChildren().clear();
        for (int i = 0; i < s.length(); i++) {
            getChildren().add(new Text("" + s.charAt(i)));
        }
        setFont(this.font);
        setFill(this.fill);
    }

    public void setFont(Font font) {
        if (font != null) {
            this.font = font;
            for (Node t : getChildren()) {
                ((Text) t).setFont(font);
            }
        }
    }

    public void setFill(Color fill) {
        if(fill != null) {
            this.fill = fill;
            for (Node t : getChildren()) {
                ((Text) t).setFill(fill);
            }
        }
    }
}


回答2:

I know I am late for the party but just in case someone was still looking for the answer:

I have been developing a small text editor app where one of core business functionalities was the possibility for user to manually set text spacing (aka "tracking"). JavaFX is awefully inconvenient in this context - there is no CSS that would take care of it, you can't set it via common controller's API and there is no way to customise used Font so it might include tracking.

Since JavaFX can't do it and one still needs to use it, there are some possibilities to mix FX with other library - like Swing. I used SwingNode and wrapped JTextField inside. JTextField offers possibility of setting Font from AWT. Fonts in AWT, unlike the ones used in JavaFX, can be customised in terms of letter tracking. To do so use Font's attributes and set TRACKING according to your needs.

Be careful - combining JavaFX with Swing might be buggy at times, even though the numerous sources state otherwise. For instance, I am facing huge problems with dynamic rendering of given JTextField in my app. I perform lots of animations (mainly related to dragging stuff all around the user space, changing fonts details rapidly etc.). But I guess as long as you need your input in static position and you won't do much animations, it should work nicely.

Btw. the fact that JavaFX still hasn't taken care of this tracking issues is a bit sad.