Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.mitrakov.self.adsbidder.client.ui;
- import java.util.*;
- import java.text.ParseException;
- import com.google.gwt.dom.client.Document;
- import com.google.gwt.event.dom.client.KeyDownHandler;
- import com.google.gwt.i18n.client.NumberFormat;
- import com.google.gwt.text.shared.AbstractRenderer;
- import com.google.gwt.user.client.ui.ValueBox;
- import static com.google.gwt.event.dom.client.KeyCodes.*;
- @SuppressWarnings("WeakerAccess")
- public class DoubleBoxEx extends ValueBox<Double> {
- static protected NumberFormat renderFormat = NumberFormat.getFormat("####.##");
- static protected NumberFormat parseFormat = NumberFormat.getFormat("####.##");
- protected KeyDownHandler doubleHandler() {
- final Set<Integer> allowedKeys = new HashSet<>(Arrays.asList(
- KEY_ONE, KEY_NUM_ONE,
- KEY_TWO, KEY_NUM_TWO,
- KEY_THREE, KEY_NUM_THREE,
- KEY_FOUR, KEY_NUM_FOUR,
- KEY_FIVE, KEY_NUM_FIVE,
- KEY_SIX, KEY_NUM_SIX,
- KEY_SEVEN, KEY_NUM_SEVEN,
- KEY_EIGHT, KEY_NUM_EIGHT,
- KEY_NINE, KEY_NUM_NINE,
- KEY_ZERO, KEY_NUM_ZERO,
- KEY_LEFT, KEY_RIGHT,
- KEY_END, KEY_HOME,
- KEY_DELETE, KEY_BACKSPACE,
- KEY_ENTER, KEY_MAC_ENTER,
- KEY_TAB,
- KEY_NUM_MINUS, 173, // 173 is "-"
- KEY_NUM_PERIOD, 190 // 190 is "."
- // note that we filter out code 188 (",") because it's a group separator (1,000,000) that may confuse users
- ));
- return event -> {
- boolean isAllowedKey = allowedKeys.contains(event.getNativeKeyCode());
- boolean isPaste1 = event.isControlKeyDown() && event.getNativeKeyCode() == KEY_V;
- boolean isPaste2 = event.isShiftKeyDown() && event.getNativeKeyCode() == KEY_INSERT;
- if (!isAllowedKey && !isPaste1 && !isPaste2)
- cancelKey();
- // note that mentioned above handling is not exhaustive: user still can copy-paste using context menu
- };
- }
- public DoubleBoxEx() {
- super(Document.get().createTextInputElement(), new AbstractRenderer<Double>() {
- public String render(Double value) { return renderFormat.format(value); }
- }, text -> {
- try {
- return parseFormat.parse(text.toString().replace(',', '.'));
- } catch (NumberFormatException e) {
- throw new ParseException(e.getMessage(), 0); // throwing is necessary to get ValueBox<T> working
- }
- }
- );
- setStyleName("am-DoubleBox");
- addKeyDownHandler(doubleHandler());
- getElement().setPropertyString("placeholder", "0.0");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement