Skip to content

Commit

Permalink
Add support to the slider to format the value
Browse files Browse the repository at this point in the history
Currently the slider always show the raw number, but often this is not
very suitable  for the user e.g. if the Number represents a unit of
measure or should be formated with a number format.

This adds a new method NebulaSlider#setLabelFormatProvider that allows
to customize the formating of the raw number.
  • Loading branch information
laeubi committed Mar 15, 2024
1 parent 7679ef6 commit a6fc901
Showing 1 changed file with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.nebula.widgets.opal.nebulaslider;

import java.util.function.IntFunction;

import org.eclipse.nebula.widgets.opal.commons.SelectionListenerUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
Expand Down Expand Up @@ -47,6 +49,8 @@ public class NebulaSlider extends Canvas {

private boolean moving = false;

private IntFunction<String> format;

/**
* Constructs a new instance of this class given its parent and a style value
* describing its behavior and appearance.
Expand Down Expand Up @@ -181,7 +185,7 @@ private void drawSelector(final GC gc) {
// And the value
gc.setForeground(renderer.getSelectorTextColor());
gc.setFont(renderer.getTextFont());
final String valueAsString = String.valueOf(value);
final String valueAsString = stringValueOf(value);
final Point textSize = gc.textExtent(valueAsString);

final int xText = hMargin + xPosition + selectorWidth / 2;
Expand All @@ -190,6 +194,29 @@ private void drawSelector(final GC gc) {
gc.drawText(valueAsString, xText - textSize.x / 2, yText - textSize.y / 2, true);
}

private String stringValueOf(int value) {
if(format != null) {
return format.apply(value);
}
return String.valueOf(value);
}

/**
* Set the format that should be used to format the given number to a string.
*
* @param format
* the format or <code>null</code> to use the default format.
*/
public void setLabelFormatProvider(IntFunction<String> format) {
checkWidget();
this.format = format;
}

public IntFunction<String> getLabelFormatProvider() {
checkWidget();
return format;
}

private void addMouseListeners() {

addListener(SWT.MouseDown, e -> {
Expand Down

0 comments on commit a6fc901

Please sign in to comment.