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 16f6baa commit 61d5901
Showing 1 changed file with 21 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 @@ -62,6 +64,7 @@ public class NebulaSlider extends Canvas {
private final Font textFont;

private boolean moving = false;
private IntFunction<String> format;

/**
* Constructs a new instance of this class given its parent and a style value
Expand Down Expand Up @@ -216,13 +219,30 @@ private void drawSelector(GC gc) {
// And the value
gc.setForeground(selectorTextColor);
gc.setFont(textFont);
final String valueAsString = String.valueOf(value);
final String valueAsString = stringValueOf(value);
final Point textSize = gc.textExtent(valueAsString);

final int xText = H_MARGIN + xPosition + SELECTOR_WIDTH / 2;
gc.drawText(valueAsString, xText - textSize.x / 2, 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) {
this.format = format;
}

private void addMouseListeners() {
addListener(SWT.MouseDown, e -> {
final int y = (getClientArea().height - SELECTOR_HEIGHT) / 2;
Expand Down

0 comments on commit 61d5901

Please sign in to comment.