当前位置: 首页 > 面试题库 >

如何限制TextField使其只能包含一个“。” 字符?JavaFX

戚升
2023-03-14
问题内容

在Internet上,我发现了一个非常有用的类,可以使用它来限制TextField。我遇到了一个问题,我的TextField只能包含一个“。”。字符。我怀疑我可以通过编写适当的正则表达式并将其设置为对该类实例的限制来处理此问题。我使用以下正则表达式:“
[0-9.-]”,但它允许用户输入的点数尽可能多。我可以请您帮助我配置TextField,以便不超过一个“。”。被允许。

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TextField;

/**
 * Created by Anton on 7/14/2015.
 */
public class RestrictiveTextField extends TextField {
private IntegerProperty maxLength = new SimpleIntegerProperty(this, "maxLength", -1);
private StringProperty restrict = new SimpleStringProperty(this, "restrict");

public RestrictiveTextField() {
    super("0");
    textProperty().addListener(new ChangeListener<String>() {

        private boolean ignore;

        @Override
        public void changed(ObservableValue<? extends String> observableValue, String s, String s1) {

            if (ignore || s1 == null)
                return;
            if (maxLength.get() > -1 && s1.length() > maxLength.get()) {
                ignore = true;
                setText(s1.substring(0, maxLength.get()));
                ignore = false;
            }

            if (restrict.get() != null && !restrict.get().equals("") && !s1.matches(restrict.get() + "*")) {
                ignore = true;
                setText(s);
                ignore = false;
            }
        }
    });
}

/**
 * The max length property.
 *
 * @return The max length property.
 */
public IntegerProperty maxLengthProperty() {
    return maxLength;
}

/**
 * Gets the max length of the text field.
 *
 * @return The max length.
 */
public int getMaxLength() {
    return maxLength.get();
}

/**
 * Sets the max length of the text field.
 *
 * @param maxLength The max length.
 */
public void setMaxLength(int maxLength) {
    this.maxLength.set(maxLength);
}

/**
 * The restrict property.
 *
 * @return The restrict property.
 */
public StringProperty restrictProperty() {
    return restrict;
}

/**
 * Gets a regular expression character class which restricts the user input.

 *
 * @return The regular expression.
 * @see #getRestrict()
 */
public String getRestrict() {
    return restrict.get();
}

/**
 * Sets a regular expression character class which restricts the user input.

 * E.g. [0-9] only allows numeric values.
 *
 * @param restrict The regular expression.
 */
public void setRestrict(String restrict) {
    this.restrict.set(restrict);
}

}


问题答案:

正则表达式有多种版本,具体取决于您要支持的内容。请注意,您不仅要匹配有效数字,而且还要匹配部分条目,因为用户必须能够对其进行编辑。因此,例如,空字符串不是有效数字,但是您当然希望用户能够在编辑时删除其中的所有内容;同样,您要允许"0.",等等。

所以你可能想要像

可选的减号,随后 任一 的任何数量的数字, 至少一个数字,句点(.),并且任何数量的数字。

正则表达式可能是-?((\\d*)|(\\d+\.\\d*))。可能还有其他方法可以做到这一点,其中有些也许更有效。而且,如果您想支持指数形式("1.3e12"),它将变得更加复杂。

要将其与一起使用TextField,建议的方法是使用TextFormatter。它TextFormatter由两部分组成:一个在文本和它所表示的值之间进行转换的转换器(Double在您的情况下,您可以使用内置的DoubleStringConverter),反之亦然,然后是一个过滤器。过滤器实现为接受TextFormatter.Change对象并返回相同类型的对象的函数。通常,您要么按Change原样保留对象并返回它(以接受Change“原样”),要么以某种方式对其进行修改。返回null代表“不变”
也是合法的。因此,在您的简单情况下,只需检查新建议的文本,看看它是否与正则表达式匹配,如果匹配则返回“原样”更改,null否则返回。

例:

import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.converter.DoubleStringConverter;

public class NumericTextFieldExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField textField = new TextField();

        Pattern validDoubleText = Pattern.compile("-?((\\d*)|(\\d+\\.\\d*))");

        TextFormatter<Double> textFormatter = new TextFormatter<Double>(new DoubleStringConverter(), 0.0, 
            change -> {
                String newText = change.getControlNewText() ;
                if (validDoubleText.matcher(newText).matches()) {
                    return change ;
                } else return null ;
            });

        textField.setTextFormatter(textFormatter);

        textFormatter.valueProperty().addListener((obs, oldValue, newValue) -> {
            System.out.println("New double value "+newValue);
        });

        StackPane root = new StackPane(textField);
        root.setPadding(new Insets(24));
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


 类似资料:
  • 我有这三个字符串: 我如何检查这些字符串中哪一个只包含字母还是只包含数字(用R表示)? 只能在字母检查中为TRUE 它对很有效,但对也很有效,这是我不想要的。 提前谢了。

  • 我正在尝试使用ansible在本地主机中安装kubectl,但收到以下错误消息: 致命:[localhost]:失败!= 我相信问题可能在于url中的回勾字符。我尝试过用单引号和反斜杠来包围它们,但都没用。这是我的剧本:

  • 代码可以很好地删除数字,但我不知道该使用什么regex,所以它也可以替换标点符号(例如`,!,],[等等) 有人能帮帮我吗?

  • 我正在尝试从product表中获取所有记录,这些记录是唯一的,但我使用leftjoin添加第二个表,其中包含这些产品的图像,但当我这样做时,它会多次返回一些产品,因为一些产品有一个或多个图像。我如何在product_images表上使用限制来确保它只得到1个图像而不是全部。下面的例子不起作用,那么这可能吗?

  • 问题内容: 我正在尝试用JavaFX制作数独游戏,但我不知道如何只允许输入一个字母。对此的答案是调用文本字段并执行以下操作: 上面的方法不适用于复制粘贴…或大量其他事情,等等。像这样使用按键监听器似乎是一个AWFUL想法。一定有更好的东西吗?是否存在文本字段的属性,仅允许输入某些字符,或仅允许输入一定数量的字符? 谢谢! 问题答案: 您可以使用来执行此操作。该可以修改都在文本字段做,如果有一个与之