Text fields
A text field turns what the user types into a value: a name, a number, a color.
It is a control with a text: everything that page says about signals, beforeChange and onChange holds here.
This page adds what only a field has: the focus, the cursor, and the rules on the text.
You will learn
- How to add a text field and read what the user types
- How to move the focus
- How to shape what the user can type
- How to ask for a number or for several lines
- How to write a field for a value of your own
Add a text field
Section titled “Add a text field”Unlike the other controls, a field draws its own text and cursor: it has a create(...) factory, and its background(...) is optional.
A field takes its font with info(...), and binds its text to a StringSignal:
private final StringSignal name = new StringSignal("");private final IntegerSignal submits = new IntegerSignal(0);TextFieldNode.create(60, 60, 480, 60).onSubmit(event -> this.submits.increment()).info(info).placeholder("Your name").placeholderColor(NameFieldUI.MUTED).text(this.name).background(RectNode.create(0, 0, 0, 0).color(NameFieldUI.ELEMENT)).marginHorizontal(12D).attach(card);TextFieldNode needs a TextInfo before it is attached; without one, the attach throws an IllegalStateException.
With the factory without a height, the field takes the height of its font plus its margins, set by FieldNode.margin, or one side at a time with marginTop(...), marginBottom(...), marginLeft(...) and marginRight(...).
The fields of this page take a dark grey background(...), and any node can be the background; their placeholderColor(...) is a grey that reads better on it than the default, the text color at half its opacity.
FieldNode.onChangeruns on each edit with aNodeFieldChangeEvent.Post:getText()is the text,getValue()the value,isValid()whether the text is a valid value.LineFieldNode.onSubmitruns when the user presses Enter and the field blurs: abeforeBlurlistener that keeps the focus prevents it.placeholder(...)shows a text while the field is empty and has no focus, in the color ofFieldNode.placeholderColor.FieldNode.cursorColorandFieldNode.selectionColorcolor the cursor and the selection; the cursor blinks.LineFieldNode.alignXplaces the text at the start, the center or the end of the field.
Move the focus
Section titled “Move the focus”A field takes the keyboard only while it has the focus: it then consumes every key and every character (Know who receives the keyboard).
- A press on the field focuses it and puts the cursor under the pointer.
- A press anywhere else blurs the field, and so do Enter in a one-line field, Escape, and the detach of the field.
- Escape keeps the typed text (Know who receives the keyboard gives what a second Escape does).
- A press on a field blurs the field that had the focus among the UIs of its UI bridge (the UIs of one window), which runs its
onBlur, then focuses the new one: the presses of the user keep one focused field at a time.
FieldNode.focus and FieldNode.blur act from your code, and focused(...) binds the focus to a signal:
final TextFieldNode search = TextFieldNode.create(60, 60, 480, 60).info(info).placeholder("Search").placeholderColor(FocusFieldUI.MUTED).focused(this.focused).beforeBlur(event -> { if (event.getNode().getText().isEmpty()) { event.cancel(); }}).background( RectNode .create(0, 0, 0, 0) .color(FocusFieldUI.ELEMENT) .effect( BorderNodeEffect .create(FocusFieldUI.ACCENT, 2F) .mode(BorderMode.IN) .width(() -> this.focused.get() ? 2F : 0F) )).marginHorizontal(12D).attach(card);RectNode.create(60, 170, 200, 60).color(FocusFieldUI.ELEMENT).onClick(event -> search.focus()).label(Text.create("Search", info)).attach(card);beforeFocus and beforeBlur can refuse the focus or keep it: here, the field keeps the focus while it is empty.
onFocus and onBlur run after the change.
Unlike a press, focus() and focused(...) blur no other field: call blur() on the field that had the focus first.
The user edits the text with the keys of every text editor:
| Keys | Action |
|---|---|
| Left, Right | Move the cursor; with Ctrl (Alt on macOS), by word |
| Home, End | Go to the start or the end of the line, or of the text in a field of one line |
| Shift with a move, or a drag of the pointer | Select |
| A double press, a triple press | Select a word, a line |
| Backspace, Delete | Erase a character; with Ctrl (Alt on macOS), a word |
| Ctrl + A, C, X, V (Cmd on macOS) | Select all, copy, cut, paste |
From your code, FieldNode.cursorPosition and FieldNode.selection give the cursor and the selection, a plain value or a signal bound both ways; FieldNode.moveCursor and FieldNode.select act like the user, with beforeCursorMove, onCursorMove, beforeSelect and onSelect.
Losing the focus clears the selection.
Shape what the user types
Section titled “Shape what the user types”TextFieldNode.create(60, 60, 480, 60).info(info).placeholder("Code").placeholderColor(RulesFieldUI.MUTED).accept(text -> text.matches("[A-Za-z ]*")).maxTextLength(6).normalize(text -> text.trim().toUpperCase()).text(this.code).background(RectNode.create(0, 0, 0, 0).color(RulesFieldUI.ELEMENT)).marginHorizontal(12D).attach(card); ab1 then Enter: the digit is refused, and the field rewrites ab as AB when it loses the focus.
FieldNode.acceptrefuses an edit whose text fails the test: the digit never appears.FieldNode.maxTextLengthcuts the text to a number of characters, also for a paste.FieldNode.normalizeturns the text into the value: the field shows the normalized text when it loses the focus, and at once for a text given by a setter or a signal.FieldNode.allowEmpty(true)lets the field be empty, with the valuenull; otherwise an empty text field holds"", and a field that reads no value from the empty text, such as a number field, takes back its last value when it loses the focus.FieldNode.markup(true)shows the markup of the text instead of its tags.
The signal follows the text as the user types it, and receives the normalized text with the rewrite. A rule that changes keeps the text asked for, as a control keeps its pending value (Keep a value that the bounds refuse).
Ask for a number
Section titled “Ask for a number”IntegerFieldNode.create(60, 60, 240, 60).min(1).max(16).step(1).value(this.players).info(info).background(RectNode.create(0, 0, 0, 0).color(NumberFieldUI.ELEMENT)).marginHorizontal(12D).attach(card);IntegerFieldNode holds an Integer between IntegerFieldNode.min and IntegerFieldNode.max:
- the user types digits, and a minus sign when
minis below0; - Up and Down, or the wheel over the focused field, add or remove
IntegerFieldNode.step; - a typed value out of the range shows as its bound when the field loses the focus;
value(...)gives the value or binds it to a signal, andchange(value)acts like the user.
An empty number field takes back 0 before any value, as allowEmpty above says; with allowEmpty(true), a bound signal receives null.
Let the user type several lines
Section titled “Let the user type several lines”MultilineTextFieldNode.create(60, 60, 480, 280).info(info).placeholder("Notes").placeholderColor(NotesFieldUI.MUTED).margin(12D).background(RectNode.create(0, 0, 0, 0).color(NotesFieldUI.ELEMENT)).attach(card);MultilineTextFieldNode wraps its text in its width.
Enter starts a new line, Up and Down move the cursor between lines, and the wheel scrolls a text taller than the field.
Write a field for your own value
Section titled “Write a field for your own value”A field for another type extends LineFieldNode and says how a text becomes a value:
public class HexColorFieldNode extends LineFieldNode<Color> {
private static final Color ELEMENT = new Color(38, 43, 53).lock();
protected HexColorFieldNode(final double x, final double y, final double width, final double height) { super(x, y, width, height); super.marginHorizontal(12D); super.background(RectNode.create(0, 0, 0, 0).color(HexColorFieldNode.ELEMENT)); }
public static HexColorFieldNode create(final double x, final double y, final double width, final double height) { return new HexColorFieldNode(x, y, width, height); }
public final <T extends HexColorFieldNode> T value(final Color value) { return super.startValue(value); }
public final <T extends HexColorFieldNode> T value(final Signal<Color> value) { return super.bindValue(value); }
@Override protected Color parse(final String text) { return text.matches("#[0-9A-Fa-f]{6}") ? Color.decode(text) : null; }
@Override protected String format(final Color value) { return String.format("#%02X%02X%02X", value.getRed(), value.getGreen(), value.getBlue()); }
@Override protected boolean accepts(final String text) { return text.matches("#?[0-9A-Fa-f]{0,6}"); }
}Full file: HexColorFieldNode.java
The constructor, the factory and the generic setters follow the pattern of every node of your own (Custom nodes).
| Method | What it does |
|---|---|
parse(text) | Turns a text into a value, or returns null when the text is not one |
format(value) | Turns a value into the text that the field shows |
accepts(text) | Refuses an edit, like accept(...), for every field of the class |
correct(value) | Brings a value back into its bounds, as min and max do |
increment(value, count) | Gives the value of count steps of Up and Down, or null for none |
startValue(...) and bindValue(...) are protected: expose them under the name of your property, as value(...) does above.
write(value, true) acts like the user, for a change(...) of your own.
HexColorFieldNode.create(60, 60, 300, 60).value(this.accent).info(info).attach(card);RectNode.create(400, 60, 140, 60).color(this.accent).attach(card);- A text field needs
info(...), binds its text to a signal, and runsonChangeon each edit andonSubmiton Enter. - A field gains the focus on a press, and loses it on a press elsewhere, Enter, Escape or its detach; a press keeps one field focused at a time.
- A focused field consumes every key; shortcuts set with
overrideFocus(true)still run. accept,maxTextLength,normalizeandallowEmptyshape the text; the field rewrites it when it loses the focus.IntegerFieldNodeholds a number betweenminandmax, stepped by the arrows and the wheel.MultilineTextFieldNodewraps its text; Enter starts a new line.- A field of your own extends
LineFieldNodeand implementsparseandformat.
Try it
Section titled “Try it”Submit only valid names.
In NameFieldUI, count a submit only when the name has at least two letters.
Solution
The listener reads the field:
.onSubmit(event -> { if (event.getNode().getText().trim().length() >= 2) { this.submits.increment(); }})Step the color.
Make Up and Down in HexColorFieldNode brighten and darken the color.
Solution
increment gives the value of a number of steps:
@Overrideprotected Color increment(final Color value, final int count) { return count > 0 ? value.brighter() : value.darker();}