首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >限制在JavaFX文本字段中输入的推荐方法

限制在JavaFX文本字段中输入的推荐方法
EN

Stack Overflow用户
提问于 2013-03-25 21:14:42
回答 5查看 20K关注 0票数 13

看起来问题是this的复制品。但我的问题是,我已经通过两种方法在JavaFX中开发了一个整型文本字段。代码如下所示

代码语言:javascript
运行
复制
public class FXNDigitsField extends TextField
{
private long m_digit;
public FXNDigitsField()
{
    super();
}
public FXNDigitsField(long number)
{
    super();
    this.m_digit = number;
    onInitialization();
}

private void onInitialization()
{
    setText(Long.toString(this.m_digit));
}

@Override
public void replaceText(int startIndex, int endIndex, String text)
{
    if (text.matches(Constants.DIGITS_PATTERN) || text.equals(Constants.EMPTY_STRING)) {
        super.replaceText(startIndex, endIndex, text);
    }
}

@Override
public void replaceSelection(String text)
{
    if (text.matches(Constants.DIGITS_PATTERN) || text.equals(Constants.EMPTY_STRING)) {
        super.replaceSelection(text);
    }
}
}

第二种方法是添加事件过滤器。

给出了代码片段。

代码语言:javascript
运行
复制
 // restrict key input to numerals.
this.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
  @Override public void handle(KeyEvent keyEvent) {
    if (!"0123456789".contains(keyEvent.getCharacter())) {
      keyEvent.consume();
    }
  }
});

我的问题是,哪种方式是诽谤?有人能帮我把右边拿起来吗?

EN

Stack Overflow用户

发布于 2014-10-31 16:26:26

在TextField中添加验证的最好方法是第三种方法。此方法让TextField安全地完成所有处理(复制/粘贴/撤消)。它不要求您扩展TextField类。它允许您在每次更改后决定如何处理新文本(将其推入逻辑,或返回到先前的值,甚至修改它)。

代码语言:javascript
运行
复制
// fired by every text property changes
textField.textProperty().addListener(
  (observable, oldValue, newValue) -> {
    // Your validation rules, anything you like
    // (! note 1 !) make sure that empty string (newValue.equals("")) 
    //   or initial text is always valid
    //   to prevent inifinity cycle
    // do whatever you want with newValue

    // If newValue is not valid for your rules
    ((StringProperty)observable).setValue(oldValue);
    // (! note 2 !) do not bind textProperty (textProperty().bind(someProperty))
    //   to anything in your code.  TextProperty implementation
    //   of StringProperty in TextFieldControl
    //   will throw RuntimeException in this case on setValue(string) call.
    //   Or catch and handle this exception.

    // If you want to change something in text
    // When it is valid for you with some changes that can be automated.
    // For example change it to upper case
    ((StringProperty)observable).setValue(newValue.toUpperCase());
  }
);
票数 12
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15615890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档