GWT 中数字文本字段的解决方案

发布于 2024-09-02 06:23:26 字数 198 浏览 5 评论 0原文

我需要一个行为与 Gxt 的 NumberField 非常相似的文本字段。不幸的是,我没有在我的应用程序中使用 Gxt,并且 GWT 2.0 还没有数字文本字段实现。

因此,目前我可以选择通过使用键盘处理程序过滤掉非数字击键来模拟 NumberField。

这是解决问题的最佳方法吗?这里有人有更好的解决方案/方法吗?

提前致谢 :)

I need a text field very similar in behavior to Gxt's NumberField. Unfortunately I am not using Gxt in my application and GWT 2.0 does not have a Numeric text field implementation as yet.

So that currently leaves me with an option to simulate a NumberField by filtering out non-numeric keystrokes using a keyboardHandler.

Is this the the best way to approach the problem? Does anyone here have a better solution/approach in mind?

Thanks in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

橙味迷妹 2024-09-09 06:23:26

在这里您可以找到我在我的一门课程中使用的代码。其功能比 GXT 的功能要有限得多,但应该能让您走上正确的轨道。

这是一个非常基本的小部件,但可以满足我的需要。

public class ValueTextBox extends TextBox {

    private int min = 0;
    private int max = 100;
    private boolean minConstrained = true;
    private boolean maxConstrained = true;
    private int minDigits = 1;
    private int step = 1;

    private KeyUpHandler keyUpHandler = new KeyUpHandler() {

        @Override
        public void onKeyUp(KeyUpEvent event) {
            if (isReadOnly() || !isEnabled()) {
                return;
            }

            int keyCode = event.getNativeEvent().getKeyCode();

            boolean processed = false;

            switch (keyCode) {
            case KeyCodes.KEY_LEFT:
            case KeyCodes.KEY_RIGHT:
            case KeyCodes.KEY_BACKSPACE:
            case KeyCodes.KEY_DELETE:
            case KeyCodes.KEY_TAB:
                if (getText().isEmpty()) {
                    setValue(formatValue(min));
                }
                return;
            case KeyCodes.KEY_UP:
                if (step != 0) {
                    increaseValue();
                    processed = true;
                }
                break;
            case KeyCodes.KEY_DOWN:
                if (step != 0) {
                    decreaseValue();
                    processed = true;
                }
                break;
            }

            if (processed) {
                cancelKey();
            }
        }

    };

    private KeyPressHandler keyPressHandler = new KeyPressHandler() {
        @Override
        public void onKeyPress(KeyPressEvent event) {

            if (isReadOnly() || !isEnabled()) {
                return;
            }

            int keyCode = event.getNativeEvent().getKeyCode();

            switch (keyCode) {
            case KeyCodes.KEY_LEFT:
            case KeyCodes.KEY_RIGHT:
            case KeyCodes.KEY_BACKSPACE:
            case KeyCodes.KEY_DELETE:
            case KeyCodes.KEY_TAB:
            case KeyCodes.KEY_UP:
            case KeyCodes.KEY_DOWN:
                return;
            }

            int index = getCursorPos();
            String previousText = getText();
            String newText;
            if (getSelectionLength() > 0) {
                newText = previousText.substring(0, getCursorPos())
                        + event.getCharCode()
                        + previousText.substring(getCursorPos()
                                + getSelectionLength(), previousText.length());
            } else {
                newText = previousText.substring(0, index)
                        + event.getCharCode()
                        + previousText.substring(index, previousText.length());
            }
            cancelKey();

            setValue(newText, true);
        }
    };

    public ValueTextBox(int value) {
        this(value, 0, 100);
    }

    public ValueTextBox(int value, int min, int max) {
        this(value, min, max, true);
    }

    public ValueTextBox(int value, int min, int max, boolean constrained) {
        this(value, min, max, constrained, constrained);
    }

    public ValueTextBox(int value, int min, int max, boolean minConstrained,
            boolean maxConstrained) {
        super();

        addKeyPressHandler(keyPressHandler);
        addKeyUpHandler(keyUpHandler);

        this.min = min;
        this.max = max;
        this.minConstrained = minConstrained;
        this.maxConstrained = maxConstrained;

        setValue(formatValue(value), false);
        setTextAlignment(TextBoxBase.ALIGN_CENTER);
        setStyleName(Resources.INSTANCE.css().fwFormEntry());
    }

    public void setMinDigits(int minDigits) {
        if (minDigits > 0) {
            this.minDigits = minDigits;

            String value = getText();
            long newValue = parseValue(value);

            setText(formatValue(newValue));
        }
    }

    public void setSteps(int step) {
        this.step = step;
    }

    protected void increaseValue() {
        if (step != 0) {
            String value = getText();
            long newValue = parseValue(value);
            newValue += step;
            if (maxConstrained && (newValue > max)) {
                return;
            }
            setValue(formatValue(newValue));
        }
    }

    protected void decreaseValue() {
        if (step != 0) {
            String value = getText();
            long newValue = parseValue(value);
            newValue -= step;
            if (minConstrained && (newValue < min)) {
                return;
            }
            setValue(formatValue(newValue));
        }
    }

    /**
     * @param value
     *            the value to format
     * @return the formatted value
     */
    protected String formatValue(long value) {
        String newValue = String.valueOf(value);

        if (minDigits > newValue.length()) {
            String leading = StringUtils.repeat("0", (minDigits - newValue
                    .length()));
            newValue = leading + newValue;
        }

        return newValue;
    }

    @Override
    public void setValue(String value) {
        setValue(value, false);
    }

    @Override
    public void setValue(String value, boolean fireEvents) {
        try {
            long newValue = parseValue(value);
            if ((maxConstrained && (newValue > max))
                    || (minConstrained && (newValue < min))) {
                return;
            }
            String prevText = getValue();
            super.setText(formatValue(newValue));
            if (fireEvents) {
                ValueChangeEvent.fireIfNotEqual(this, getValue(), prevText);
            }
        } catch (Exception ex) {
            // Do Nothing
            System.out.println(ex.getMessage());
        }
    }

    /**
     * @param value
     *            the value to parse
     * @return the parsed value
     */
    protected long parseValue(String value) {
        return Long.valueOf(value);
    }
}

更新:代码位于 https:// github.com/ctasada/GWT-Eureka

Here you can find the code that I use in one of my classes. The features are much more limited that those of GXT, but should put you in the proper track.

It's a really basic widget, but does what I need to.

public class ValueTextBox extends TextBox {

    private int min = 0;
    private int max = 100;
    private boolean minConstrained = true;
    private boolean maxConstrained = true;
    private int minDigits = 1;
    private int step = 1;

    private KeyUpHandler keyUpHandler = new KeyUpHandler() {

        @Override
        public void onKeyUp(KeyUpEvent event) {
            if (isReadOnly() || !isEnabled()) {
                return;
            }

            int keyCode = event.getNativeEvent().getKeyCode();

            boolean processed = false;

            switch (keyCode) {
            case KeyCodes.KEY_LEFT:
            case KeyCodes.KEY_RIGHT:
            case KeyCodes.KEY_BACKSPACE:
            case KeyCodes.KEY_DELETE:
            case KeyCodes.KEY_TAB:
                if (getText().isEmpty()) {
                    setValue(formatValue(min));
                }
                return;
            case KeyCodes.KEY_UP:
                if (step != 0) {
                    increaseValue();
                    processed = true;
                }
                break;
            case KeyCodes.KEY_DOWN:
                if (step != 0) {
                    decreaseValue();
                    processed = true;
                }
                break;
            }

            if (processed) {
                cancelKey();
            }
        }

    };

    private KeyPressHandler keyPressHandler = new KeyPressHandler() {
        @Override
        public void onKeyPress(KeyPressEvent event) {

            if (isReadOnly() || !isEnabled()) {
                return;
            }

            int keyCode = event.getNativeEvent().getKeyCode();

            switch (keyCode) {
            case KeyCodes.KEY_LEFT:
            case KeyCodes.KEY_RIGHT:
            case KeyCodes.KEY_BACKSPACE:
            case KeyCodes.KEY_DELETE:
            case KeyCodes.KEY_TAB:
            case KeyCodes.KEY_UP:
            case KeyCodes.KEY_DOWN:
                return;
            }

            int index = getCursorPos();
            String previousText = getText();
            String newText;
            if (getSelectionLength() > 0) {
                newText = previousText.substring(0, getCursorPos())
                        + event.getCharCode()
                        + previousText.substring(getCursorPos()
                                + getSelectionLength(), previousText.length());
            } else {
                newText = previousText.substring(0, index)
                        + event.getCharCode()
                        + previousText.substring(index, previousText.length());
            }
            cancelKey();

            setValue(newText, true);
        }
    };

    public ValueTextBox(int value) {
        this(value, 0, 100);
    }

    public ValueTextBox(int value, int min, int max) {
        this(value, min, max, true);
    }

    public ValueTextBox(int value, int min, int max, boolean constrained) {
        this(value, min, max, constrained, constrained);
    }

    public ValueTextBox(int value, int min, int max, boolean minConstrained,
            boolean maxConstrained) {
        super();

        addKeyPressHandler(keyPressHandler);
        addKeyUpHandler(keyUpHandler);

        this.min = min;
        this.max = max;
        this.minConstrained = minConstrained;
        this.maxConstrained = maxConstrained;

        setValue(formatValue(value), false);
        setTextAlignment(TextBoxBase.ALIGN_CENTER);
        setStyleName(Resources.INSTANCE.css().fwFormEntry());
    }

    public void setMinDigits(int minDigits) {
        if (minDigits > 0) {
            this.minDigits = minDigits;

            String value = getText();
            long newValue = parseValue(value);

            setText(formatValue(newValue));
        }
    }

    public void setSteps(int step) {
        this.step = step;
    }

    protected void increaseValue() {
        if (step != 0) {
            String value = getText();
            long newValue = parseValue(value);
            newValue += step;
            if (maxConstrained && (newValue > max)) {
                return;
            }
            setValue(formatValue(newValue));
        }
    }

    protected void decreaseValue() {
        if (step != 0) {
            String value = getText();
            long newValue = parseValue(value);
            newValue -= step;
            if (minConstrained && (newValue < min)) {
                return;
            }
            setValue(formatValue(newValue));
        }
    }

    /**
     * @param value
     *            the value to format
     * @return the formatted value
     */
    protected String formatValue(long value) {
        String newValue = String.valueOf(value);

        if (minDigits > newValue.length()) {
            String leading = StringUtils.repeat("0", (minDigits - newValue
                    .length()));
            newValue = leading + newValue;
        }

        return newValue;
    }

    @Override
    public void setValue(String value) {
        setValue(value, false);
    }

    @Override
    public void setValue(String value, boolean fireEvents) {
        try {
            long newValue = parseValue(value);
            if ((maxConstrained && (newValue > max))
                    || (minConstrained && (newValue < min))) {
                return;
            }
            String prevText = getValue();
            super.setText(formatValue(newValue));
            if (fireEvents) {
                ValueChangeEvent.fireIfNotEqual(this, getValue(), prevText);
            }
        } catch (Exception ex) {
            // Do Nothing
            System.out.println(ex.getMessage());
        }
    }

    /**
     * @param value
     *            the value to parse
     * @return the parsed value
     */
    protected long parseValue(String value) {
        return Long.valueOf(value);
    }
}

Update: The code is available in https://github.com/ctasada/GWT-Eureka

恋竹姑娘 2024-09-09 06:23:26

这是一个简单的 KeyPressHandler,允许用户输入十进制数字;

public void onKeyPress(KeyPressEvent event){
    TextBox sender = (TextBox)event.getSource();

    if (sender.isReadOnly() || !sender.isEnabled()) {
        return;
    }

    Character charCode = event.getCharCode();
    int unicodeCharCode = event.getUnicodeCharCode();

    // allow digits, '.' and non-characters
    if (!(Character.isDigit(charCode) || charCode == '.' || unicodeCharCode == 0)){
        sender.cancelKey();
    }
}

Here is a simple KeyPressHandler to allow the user to input decimal numbers;

public void onKeyPress(KeyPressEvent event){
    TextBox sender = (TextBox)event.getSource();

    if (sender.isReadOnly() || !sender.isEnabled()) {
        return;
    }

    Character charCode = event.getCharCode();
    int unicodeCharCode = event.getUnicodeCharCode();

    // allow digits, '.' and non-characters
    if (!(Character.isDigit(charCode) || charCode == '.' || unicodeCharCode == 0)){
        sender.cancelKey();
    }
}
当梦初醒 2024-09-09 06:23:26

不知道这些类何时添加到 GWT,但它们对我来说工作得很好,不需要任何额外的代码:

com.google.gwt.user.client.ui.DoubleBox
com.google.gwt.user.client.ui.IntegerBox
com.google.gwt.user.client.ui.LongBox 

对于更高级的验证,您可能需要使用一些自定义解析器覆盖它们的基类 ValueBox...

Don't know when these classes were added to GWT, but they work fine for me without any extra code:

com.google.gwt.user.client.ui.DoubleBox
com.google.gwt.user.client.ui.IntegerBox
com.google.gwt.user.client.ui.LongBox 

For more advanced validation you may want to overwrite their base class ValueBox with some custom Parser...

合约呢 2024-09-09 06:23:26

Carlos Tasada 答案有效,但包含一个错误:您应该在 switch/case 块之前在 onKeyPress 处理程序中添加 event.isShiftKeyDown() 检查。否则它会传递一些像“(”这样的符号。

Carlos Tasada answer works, but contains a bug: you should add event.isShiftKeyDown() check in onKeyPress handler before switch/case block. It will pass some symbols like '(' otherwise.

孤独患者 2024-09-09 06:23:26

根据朱利安唐斯的回答,你可以这样做:

text.addKeyPressHandler(new KeyPressHandler() {

        @Override
        public void onKeyPress(KeyPressEvent event) {
            TextBox sender = (TextBox) event.getSource();

            if (sender.isReadOnly() || !sender.isEnabled()) {
                return;
            }
            if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
                return;
            }

            Character charCode = event.getCharCode();

            try{
                Double.parseDouble(sender.getText().concat(charCode.toString()));
            }
            catch(Exception e){
                sender.cancelKey();
            }
        }
    });

Based on Julian Downes answer you can do this:

text.addKeyPressHandler(new KeyPressHandler() {

        @Override
        public void onKeyPress(KeyPressEvent event) {
            TextBox sender = (TextBox) event.getSource();

            if (sender.isReadOnly() || !sender.isEnabled()) {
                return;
            }
            if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
                return;
            }

            Character charCode = event.getCharCode();

            try{
                Double.parseDouble(sender.getText().concat(charCode.toString()));
            }
            catch(Exception e){
                sender.cancelKey();
            }
        }
    });
|煩躁 2024-09-09 06:23:26

这是我的 NumberField 实现。功能与卡洛斯的版本非常相似,但额外支持十进制输入和非数字键过滤。

public class NumberBox extends TextBox
{
private boolean isDecimal = false;

public NumberBox( )
{
}

public boolean isDecimal( )
{
    return isDecimal;
}

public void setDecimal( boolean isDecimal )
{
    this.isDecimal = isDecimal;
}

public Integer getIntegerValue( )
{
    return ( StringUtil.isEmpty( getSanitizedValue( ) ) ) ? null : Integer.parseInt( getSanitizedValue( ) );
}

@Override
protected void initialize( )
{
    super.initialize( );
    addStyleName( "number" );

    this.addKeyPressHandler( new KeyPressHandler( )
    {
        public void onKeyPress( KeyPressEvent event )
        {
            if ( !isEnabled( ) || isReadOnly( ) )
                return;

            int keyCode = event.getNativeEvent( ).getKeyCode( );

            // allow special keys
            if ( ( keyCode == KeyCodes.KEY_BACKSPACE )
                    || ( keyCode == KeyCodes.KEY_DELETE )
                    || ( keyCode == KeyCodes.KEY_ENTER ) || ( keyCode == KeyCodes.KEY_ESCAPE ) || ( keyCode == KeyCodes.KEY_RIGHT )
                    || ( keyCode == KeyCodes.KEY_LEFT ) || ( keyCode == KeyCodes.KEY_TAB ) )
                return;

            // check for decimal '.'
            if ( isDecimal( ) && '.' == (char)keyCode && !getValue( ).contains( "." ) )
                return;

            // filter out non-digits
            if ( Character.isDigit( charCode ) )
                return;

            cancelKey( );
        }
    } );
}

PS


:超类 TextBox 是一个自定义类,它扩展了 GWT TextBox,并具有一些附加的应用程序特定功能。方法initialize() 基本上是在TextBox 构造函数内部调用的,而getSanitizedValue 通过修剪进行一些基本的健全性检查。

Here is my implementation of NumberField. Very similar in functionality to Carlos's version, but with additional support for decimal input and non-numeric key filtering.

public class NumberBox extends TextBox
{
private boolean isDecimal = false;

public NumberBox( )
{
}

public boolean isDecimal( )
{
    return isDecimal;
}

public void setDecimal( boolean isDecimal )
{
    this.isDecimal = isDecimal;
}

public Integer getIntegerValue( )
{
    return ( StringUtil.isEmpty( getSanitizedValue( ) ) ) ? null : Integer.parseInt( getSanitizedValue( ) );
}

@Override
protected void initialize( )
{
    super.initialize( );
    addStyleName( "number" );

    this.addKeyPressHandler( new KeyPressHandler( )
    {
        public void onKeyPress( KeyPressEvent event )
        {
            if ( !isEnabled( ) || isReadOnly( ) )
                return;

            int keyCode = event.getNativeEvent( ).getKeyCode( );

            // allow special keys
            if ( ( keyCode == KeyCodes.KEY_BACKSPACE )
                    || ( keyCode == KeyCodes.KEY_DELETE )
                    || ( keyCode == KeyCodes.KEY_ENTER ) || ( keyCode == KeyCodes.KEY_ESCAPE ) || ( keyCode == KeyCodes.KEY_RIGHT )
                    || ( keyCode == KeyCodes.KEY_LEFT ) || ( keyCode == KeyCodes.KEY_TAB ) )
                return;

            // check for decimal '.'
            if ( isDecimal( ) && '.' == (char)keyCode && !getValue( ).contains( "." ) )
                return;

            // filter out non-digits
            if ( Character.isDigit( charCode ) )
                return;

            cancelKey( );
        }
    } );
}

}


PS: Superclass TextBox is a custom class extending GWT TextBox with some additional application specific features. The method initialize() is basically invoked inside the TextBox constructor, and getSanitizedValue does some basic sanity checks with trimming.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文