How to set JFormattedTextField value with placeholder character?

I have a formatted text box for the ip address:

ipmask = new MaskFormatter("###.###.###.###"); ipmask.setPlaceholderCharacter(' '); field = new JFormattedTextField(ipmask); 

field.setValue("111.222.333.444"); works but

field.setValue(" 10.222.333.444"); does not work

field.setValue("10 .222.333.444"); does not work

field.setValue("10.222.333.444"); does not work

What is the correct way to set the value?

+4
source share
3 answers

Rather strange, but that came up in another question (in Java: network settings window ). After digging out, the Sun RegexFormatter implementation appears (see http://java.sun.com/products/jfc/tsc/articles/reftf/ ; download the source code http://java.sun.com/products/ jfc / tsc / articles / reftf / RegexFormatter.java ), which you can use as follows:

 JFormattedTextField ipAddress; try{ RegexFormatter ipmask = new RegexFormatter("\\d{0,3}\\.\\d{0,3}\\.\\d{0,3}\\.\\d{0,3}"); ipmask.setOverwriteMode(false); ipAddress = new JFormattedTextField(ipmask); }catch(Exception e1){ } ipAddress.setValue("255.255.255.255"); 

You probably moved from here, but thought that I would stick with this just in case someone else was wandering around.

+5
source

spaces are not considered numbers (#) and. count anything. unfortunately, you cannot match the IP address with MaskFormatter unless you find a way to have multiple MaskFormatters for 1 JFormattedTextField.

easier

 if (field.getValue().matches("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")) //do something 

EDIT: you will have to use a regular JTextField and check it out

+1
source

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); } } 
0
source

Source: https://habr.com/ru/post/1286020/


All Articles