Java Reference
In-Depth Information
Figure 16-6. Formatted JFormattedTextField date and time input
Number Formats
Numbers work similarly to dates, just with the java.text.NumberFormat class, instead of the
DateFormat class. The localization that can be done here is with getCurrencyInstance() ,
getInstance() , getIntegerInstance() , getNumberInstance() , and getPercentInstance() .
The NumberFormat class will deal with the placement of the necessary commas, periods,
percent signs, and so on. While inputting the numbers, extra characters like commas for thousands
aren't required. The component will add them after they are input where appropriate, as
shown in the example in Figure 16-7. Notice the positions of decimal points and commas and
how they differ from locale to locale.
Figure 16-7. Formatted JFormattedTextField numeric input
Listing 16-8 shows the program that generated Figure 16-7. Each input field starts with a
value of 2424.50. In the case of the integer version, the input value is rounded. When setting the
contents of a JFormattedTextField , use the setValue() method, not the setText() method.
This will ensure that the text contents are validated.
Listing 16-8. Formatted Numeric Input
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
import java.text.*;
import java.util.*;
 
Search WWH ::




Custom Search