I tried to use the layout format, but it is not very good in our situation, so I came up with this method using Regex and instant check for user input.
This code is generated using gui builder:
jFormattedTextField2 = new javax.swing.JFormattedTextField(); jFormattedTextField2.setHorizontalAlignment(jFormattedTextField2.CENTER); jFormattedTextField2.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent evt) { jFormattedTextField2CaretUpdate(evt); } });
Here, each time the field is updated, the input will be checked using pairing:
private void jFormattedTextField2CaretUpdate(javax.swing.event.CaretEvent evt) { // validation happen here and the text is red if IP is invalid final String regex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"; final Pattern pattern = Pattern.compile(regex); String ip = jFormattedTextField2.getText(); Matcher m = pattern.matcher(ip); jFormattedTextField2.setForeground(Color.red); if (m.matches()) { jFormattedTextField2.setForeground(Color.black); } }
source share