Slider
Slider is a vanilla slider over a range of numbers with an optional step and custom value text, like the game's FOV and volume sliders.
A vanilla slider over a range of numbers, showing "label: value" on the slider itself, like vanilla's FOV or volume sliders. The player drags the knob, clicks the track, or uses the arrow keys while it is focused.
// Whole numbers: step 1, cast in onChange
Slider.builder("renderDistance")
.label(Text.translatable("mymod.distance", "Distance"))
.range(2, 32).step(1)
.value(() -> config.distance)
.onChange(v -> config.distance = (int) v)
.build();
// A fraction shown as a percentage
Slider.builder("opacity")
.label(Text.translatable("mymod.opacity", "Opacity"))
.range(0, 1).step(0.05)
.value(() -> config.opacity)
.valueText(v -> Text.literal(Math.round(v * 100) + "%"))
.onChange(v -> config.opacity = v)
.build();
Builder#
| Method | Required | Default | Notes |
|---|---|---|---|
label(Supplier<Text>) / label(Text) |
yes | the text before ": value" | |
range(double min, double max) |
yes | both ends inclusive; min must be less than max, both finite |
|
value(DoubleSupplier) |
yes | your current value; re-read on every refresh and during drags | |
onChange(DoubleConsumer) |
yes | stores a new value; main thread | |
step(double) |
no | 0: any value |
the distance between values: 1 for whole numbers, 0.1 for one decimal. At most max - min. |
valueText(DoubleFunction<Text>) |
no | the number | how the value is shown after "label: " |
enabled, tooltip, visible |
no | options every widget has |
build() throws if a required field is missing, the range is empty or infinite, or the step is negative or
larger than the range.
Behaviour#
- Values are
doubles in[min, max]. With a step they aremin + k * step; if the step doesn't divide the range, the highest value is the last step belowmax. onChangeruns for every distinct snapped value while the player drags, not only on release, and only when the value changes. Keep it fast; save to disk from the screen's Done button.- A
valueoutside the range shows clamped. - An arrow key moves the value by one step, or by 1% of the range without a step.
- The default text has as many decimals as the step (none for whole steps, two without a step), so
12or0.25. UsevalueTextfor units or names:v -> Text.literal((int) v + " chunks"), orv -> v == 0 ? Text.translatable("mymod.off", "Off") : Text.literal(String.valueOf((int) v)). - Steps such as
0.1give exact values (0.3, not 0.30000000000000004). - Footer: no.
Test it#
host.slide("renderDistance", 12); // snapped and clamped as a drag would be
Rendered as [slider renderDistance] Distance: 12.
See also#
- Javadoc: Slider
- NumberField: for a number the player types exactly.