-1

This is somewhat of an extension to this question: Formatting JTextField to accept three digits at most, but anything up to 1-3 digits can be typed

The following code allows me to enter value from 1-3 digits (ie. 1, 10, 100):

NumberFormat amountFormat = NumberFormat.getNumberInstance();
amountFormat.setMinimumIntegerDigits(1);
amountFormat.setMaximumIntegerDigits(3);
amountFormat.setMaximumFractionDigits(0);

amountField = new JFormattedTextField(amountFormat);

What I would like is to add leading zeros if 1 or 2 digits are entered (ie. 1 or 01 => 001, 10 => 010).

Perhaps I can somehow use the string formatter?

String.format("%03d", num)
Community
  • 1
  • 1
Ali
  • 558
  • 7
  • 28

2 Answers2

0

You can use regular expressions, for example:

if (someString.matches("^\\d{1,2}$")) {
    String appendZero = "0"+someString
}

The if returns true if someString contains exactly two digits.

qtips
  • 625
  • 6
  • 17
  • Doesn't the String's format function do all the checking for me? – Ali Mar 16 '15 at 15:08
  • if you simply want to padd with zeroes if at least 3 digits are not entered, then yes. String.format("%03d", 1) = 001 String.format("%03d", 10) = 010 String.format("%03d", 1) = 100 String.format("%03d", 1011) = 1011 Test it - http://www.javarepl.com/console.html – qtips Mar 16 '15 at 15:21
  • My question is how do I incorporate the checking/formatting while using NumberFormat, JFormattedTextField? – Ali Mar 16 '15 at 15:28
  • You want to show the padded zeroes in the textfield as the user types in? Then you must have a listener (PropertyChangeListener) that captures the value while typing, padds the values and updates the textfield or some other label. The padding can be done by the String.format(). http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html – qtips Mar 16 '15 at 15:43
0

I think I did not ask the question correctly, but the (simplest) answer to my current question would be to use the string format when displaying the given input (as suggested in the original post).

Ali
  • 558
  • 7
  • 28