Domanda

I have created a custom TableCell cellfactory. I want it to accept only Decimal input (numeric & only one dot(.)). Below is the code for replaceText & replaceSelection but it doesnt allow me to enter anything.

        @Override
        public void replaceText(int start, int end, String text) {
            if (text.matches("/^\\d*\\.?\\d*$/")) {
                super.replaceText(start, end, text);
            }
        }

        @Override
        public void replaceSelection(String text) {
            if (text.matches("/\\d*\\.?\\d*$/")) {
                super.replaceSelection(text);
            }
        }
    };
È stato utile?

Soluzione

Java regexes aren't surrounded by '/'. Depending on the actual behavior you want, you need something like

final Pattern pattern = Pattern.compile("^\\d*\\.?\\d*$");
final TextField tf = new TextField() {
   @Override
   public void replaceText(int start, int end, String text) {
       String newText = getText().substring(0, start)+text+getText().substring(end);
        if (pattern.matcher(newText).matches()) {
            super.replaceText(start, end, text);
        }
    }

    @Override
    public void replaceSelection(String text) {
        int start = getSelection().getStart();
        int end = getSelection().getEnd();
        String newText = getText().substring(0, start)+text+getText().substring(end);
        if (pattern.matcher(newText).matches()) {
            super.replaceSelection(text);
        }
    }
};

Altri suggerimenti

Your regex has a flaw. It can even match with empty string as you are making everything optional in there.

text.matches("/^\\d*\\.?\\d*$/")

So Change it like below:

text.matches("/^\\d+(\\.\\d+)?$/")

Here it means mandatory digits at the begin(^\\d+), and then optional dot and digits after((\\.\\d+)?$).

You are replacing the text afterwards. I suppose it would be better to not change the text directly and listen to KeyEvent.KEY_PRESSED on the parent (with EventFilter).

You get the event then and check the character if it is numeric or not. You consume the event if you don't want it to show in the input.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top