Java – jtextarea contains only numbers, but negative values are allowed
•
Java
I have a jtextarea, just accept numbers This is my code:
DocumentFilter onlyNumberFilter = new AxisJTextFilter(); final JTextArea areaTextoXMin = new JTextArea(String.valueOf(xMin)); ((AbstractDocument)areaTextoXMin.getDocument()).setDocumentFilter(onlyNumberFilter);
Applies to positive numbers, but not negative numbers How can I solve this problem?
Editor: sorry, axisjtextfilter was found on the Internet, I forgot Its code is:
import javax.swing.text.*; import java.util.regex.*; public class AxisJTextFilter extends DocumentFilter { public void insertString(DocumentFilter.FilterBypass fb,int offset,String text,AttributeSet attr) throws BadLocationException { StringBuilder sb = new StringBuilder(); sb.append(fb.getDocument().getText(0,fb.getDocument().getLength())); sb.insert(offset,text); if(!containsOnlyNumbers(sb.toString())) return; fb.insertString(offset,text,attr); } public void replace(DocumentFilter.FilterBypass fb,int length,fb.getDocument().getLength())); sb.replace(offset,offset + length,text); if(!containsOnlyNumbers(sb.toString())) return; fb.replace(offset,length,attr); } public boolean containsOnlyNumbers(String text) { Pattern pattern = Pattern.compile("\\d*(\\.\\d{0,3})?"); Matcher matcher = pattern.matcher(text); boolean isMatch = matcher.matches(); return isMatch; } }
Solution
Try modifying the regular expression (int validation method containsonlynumbers)
Pattern pattern = Pattern.compile("^[\\-\\+]?\\d+(\\.\\d+)?$");
This will accept the following numbers:
> 1234 > -1234 > 1234 > 1234.1234
I hope it helps
UDI
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码