Specifying Width with FieldPosition
The Java core
API
does not include any classes that pad numbers with spaces like the
traditional I/O APIs in Fortran, C, and other languages. Part of the
reason is that it’s no longer a valid assumption that all
output is written in a monospaced font on a VT-100 terminal.
Therefore, spaces are insufficient to line up numbers in tables.
Ideally, if you’re writing tabular data in a GUI, you can use a
real table component like JTable
in the Java
foundation classes. If that’s not possible, you can measure the
width of the string using a FontMetrics
object and
offset the position at which you draw the string. And if you are
outputting to a terminal or a monospaced font, then you can manually
prefix the string with the right number of spaces.
The
java.text.FieldPosition
class separates strings into their component parts, called
fields. (This is another unfortunate example of
an overloaded term. These fields have nothing to do with the fields
of a Java class.) For example, a typical date string can be separated
into 18 fields including era, year, month, day, date, hour, minute,
second, and so on. Of course, not all of these may be present in any
given string. For example, 1999 CE includes only a year and an era
field. The different fields that can be parsed are represented as
public
final
static
int
fields
(there’s that annoying overloading again) in the corresponding
format class. The java.text.DateFormat
class defines these kinds of fields as mnemonic ...
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.