看起来问题是this的复制品。但我的问题是,我已经通过两种方法在JavaFX中开发了一个整型文本字段。代码如下所示
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);
}
}
}第二种方法是添加事件过滤器。
给出了代码片段。
// 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();
}
}
});我的问题是,哪种方式是诽谤?有人能帮我把右边拿起来吗?
发布于 2014-10-31 16:26:26
在TextField中添加验证的最好方法是第三种方法。此方法让TextField安全地完成所有处理(复制/粘贴/撤消)。它不要求您扩展TextField类。它允许您在每次更改后决定如何处理新文本(将其推入逻辑,或返回到先前的值,甚至修改它)。
// 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());
}
);https://stackoverflow.com/questions/15615890
复制相似问题