如何验证 swt 文本小部件是否为十进制值

发布于 2024-12-06 06:18:30 字数 3048 浏览 0 评论 0原文

在 swt 中,文本小部件允许任何字符串。 但是,最适合输入 Decimal 值的 SWT 小部件是什么?

我找到了两个答案:

  1. 首先,实现VerifyKeyListener和VerifyListener,适用于法国十进制表示法,但简单且易于实现:
package test.actions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Text;

public final class AmountVerifyKeyListener implements VerifyListener, VerifyKeyListener             {

    private static final String REGEX = "^[-+]?[0-9]*[,]?[0-9]{0,2}+$"; 

    private static final Pattern pattern = Pattern.compile(REGEX);  

    public void verifyText(VerifyEvent verifyevent) {
        verify(verifyevent);
    }

    public void verifyKey(VerifyEvent verifyevent) {
        verify(verifyevent);
    }

    private void verify (VerifyEvent e) {
        String string = e.text;
        char[] chars = new char[string.length()];
        string.getChars(0, chars.length, chars, 0);

        Text text = (Text)e.getSource();

        if ( ( ",".equals(string) || ".".equals(string) ) && text.getText().indexOf(',') >= 0 ) {
            e.doit = false;
            return;
        } 

        for (int i = 0; i < chars.length; i++) {
            if (!(('0' <= chars[i] && chars[i] <= '9') || chars[i] == '.' ||  chars[i] == ',' || chars[i] == '-')) {
                e.doit = false;
                return;
            } 


            if ( chars[i] == '.' ) {
                chars[i] = ',';
            }
        }

        e.text = new String(chars);

        final String oldS = text.getText();
        String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
        Matcher matcher = pattern.matcher(newS);
        if ( !matcher.matches() ) {
            e.doit = false;
            return;
        }

    }
}

以及与verifyKeyListener关联的主类:

package test.actions;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class TestMain {

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(2, false));

        final Text text = new Text(shell, SWT.NONE);

        text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        text.addVerifyListener(new AmountVerifyKeyListener() ) ;

        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
    }

}
  1. 使用星云项目中的FormattedText:http://eclipse.org/nebula/

有人看到另一个解决方案吗?

In swt, text widget allow any string.
But What is the most appropriate SWT widget in which to enter a Decimal value?

I found two answers :

  1. First, implement the VerifyKeyListener and VerifyListener, work for french decimal notation, but simple and easy to implement :
package test.actions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Text;

public final class AmountVerifyKeyListener implements VerifyListener, VerifyKeyListener             {

    private static final String REGEX = "^[-+]?[0-9]*[,]?[0-9]{0,2}+$"; 

    private static final Pattern pattern = Pattern.compile(REGEX);  

    public void verifyText(VerifyEvent verifyevent) {
        verify(verifyevent);
    }

    public void verifyKey(VerifyEvent verifyevent) {
        verify(verifyevent);
    }

    private void verify (VerifyEvent e) {
        String string = e.text;
        char[] chars = new char[string.length()];
        string.getChars(0, chars.length, chars, 0);

        Text text = (Text)e.getSource();

        if ( ( ",".equals(string) || ".".equals(string) ) && text.getText().indexOf(',') >= 0 ) {
            e.doit = false;
            return;
        } 

        for (int i = 0; i < chars.length; i++) {
            if (!(('0' <= chars[i] && chars[i] <= '9') || chars[i] == '.' ||  chars[i] == ',' || chars[i] == '-')) {
                e.doit = false;
                return;
            } 


            if ( chars[i] == '.' ) {
                chars[i] = ',';
            }
        }

        e.text = new String(chars);

        final String oldS = text.getText();
        String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
        Matcher matcher = pattern.matcher(newS);
        if ( !matcher.matches() ) {
            e.doit = false;
            return;
        }

    }
}

And the main class associated to the verifyKeyListener :

package test.actions;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class TestMain {

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(2, false));

        final Text text = new Text(shell, SWT.NONE);

        text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        text.addVerifyListener(new AmountVerifyKeyListener() ) ;

        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
    }

}
  1. Use the FormattedText from the nebula project : http://eclipse.org/nebula/

Somebody see another solution ?

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

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

发布评论

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

评论(3

江湖彼岸 2024-12-13 06:18:30

一种更干净、更简单的方法是使用 Double.parseString() 并捕获 NumberFormatException 来确定其中的文本是否可以转换为双精度。

A cleaner and easier way would be to use Double.parseString() and catch the NumberFormatException's to figure out if the text in it can be converted to a double.

东北女汉子 2024-12-13 06:18:30
  • 对于 Double 值的验证,您必须考虑到 Double 中可能包含 E 等字符,并且在键入时像“4e-”这样的部分输入应该有效,以允许最终输入“4e-3”。部分表达式可能会给出 Double.parseDouble(partialExpression) 的 NumberFormatException

  • 另请参阅我在以下相关问题中的回答:
    如何设置掩码到 SWT 文本仅允许小数

  • (进一步说明:如果只想允许整数值,则可以使用微调器而不是文本字段。)

  • For the validation of Double values you have to consider that characters like E may be included in Doubles and that partial input like "4e-" should be valid while typing to allow to finally enter "4e-3". The partial expressions might give a NumberFormatException for Double.parseDouble(partialExpression)

  • Also see my answer at following related question:
    How to set a Mask to a SWT Text to only allow Decimals

  • (Further note: If one only wants to allow Integer values a Spinner can be used instead of a text field.)

魔法唧唧 2024-12-13 06:18:30

为什么不在小部件上使用简单的正则表达式,如下所示:

    if(Text.getText().matches("^[0-9]+$")) {
       show an error dialog or similar
    }

Why not a simple regex on the widget like the following:

    if(Text.getText().matches("^[0-9]+$")) {
       show an error dialog or similar
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文