What is the recommended way to make a numeric Text

2019-01-02 23:53发布

I need to restrict input into a TextField to integers. Any advice?

22条回答
SAY GOODBYE
2楼-- · 2019-01-03 00:22

The preffered answer can be even smaller if you make use of Java 1.8 Lambdas

textfield.textProperty().addListener((observable, oldValue, newValue) -> {
    if (!newValue.matches("\\d*")) {
        textfield.setText(newValue.replaceAll("[^\\d]", ""));
    }
});
查看更多
Viruses.
3楼-- · 2019-01-03 00:23

Starting with JavaFX 8u40, you can set a TextFormatter object on a text field:

UnaryOperator<Change> filter = change -> {
    String text = change.getText();

    if (text.matches("[0-9]*")) {
        return change;
    }

    return null;
};
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
fieldNport = new TextField();
fieldNport.setTextFormatter(textFormatter);

This avoids both subclassing and duplicate change events which you will get when you add a change listener to the text property and modify the text in that listener.

查看更多
混吃等死
4楼-- · 2019-01-03 00:23

This one worked for me.

public void RestrictNumbersOnly(TextField tf){
    tf.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, 
            String newValue) {
            if (!newValue.matches("|[-\\+]?|[-\\+]?\\d+\\.?|[-\\+]?\\d+\\.?\\d+")){
                tf.setText(oldValue);
            }
        }
    });
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-03 00:23

i want to help with my idea from combine Evan Knowles answer with text formater from java fx 8

    textField.setTextFormatter(new TextFormatter<>(c -> {
        if (!c.getControlNewText().matches("\\d*")) 
            return null;
        else
            return c;
    }));

so good luck ;) keep calm and code java

查看更多
一夜七次
6楼-- · 2019-01-03 00:24

I know this is a rather old thread, but for future readers here is another solution I found quite intuitive:

public class NumberTextField extends TextField
{

    @Override
    public void replaceText(int start, int end, String text)
    {
        if (validate(text))
        {
            super.replaceText(start, end, text);
        }
    }

    @Override
    public void replaceSelection(String text)
    {
        if (validate(text))
        {
            super.replaceSelection(text);
        }
    }

    private boolean validate(String text)
    {
        return text.matches("[0-9]*");
    }
}

Edit: Thanks none_ and SCBoy for your suggested improvements.

查看更多
7楼-- · 2019-01-03 00:27

Starting from Java SE 8u40, for such need you can use an "integer" Spinner allowing to safely select a valid integer by using the keyboard's up arrow/down arrow keys or the up arrow/down arrow provided buttons.

You can also define a min, a max and an initial value to limit the allowed values and an amount to increment or decrement by, per step.

For example

// Creates an integer spinner with 1 as min, 10 as max and 2 as initial value
Spinner<Integer> spinner1 = new Spinner<>(1, 10, 2);
// Creates an integer spinner with 0 as min, 100 as max and 10 as initial 
// value and 10 as amount to increment or decrement by, per step
Spinner<Integer> spinner2 = new Spinner<>(0, 100, 10, 10);

Example of result with an "integer" spinner and a "double" spinner

enter image description here

A spinner is a single-line text field control that lets the user select a number or an object value from an ordered sequence of such values. Spinners typically provide a pair of tiny arrow buttons for stepping through the elements of the sequence. The keyboard's up arrow/down arrow keys also cycle through the elements. The user may also be allowed to type a (legal) value directly into the spinner. Although combo boxes provide similar functionality, spinners are sometimes preferred because they don't require a drop-down list that can obscure important data, and also because they allow for features such as wrapping from the maximum value back to the minimum value (e.g., from the largest positive integer to 0).

More details about the Spinner control

查看更多
登录 后发表回答