Java Reference
In-Depth Information
public FormattedWriter(Writer output, int width) {
this(output, false, width, RIGHT
_
JUSTIFIED);
}
// Constructor with a specified field width and justification
public FormattedWriter(Writer output, int width, int justification) {
this(output, false, width, justification);
}
// Constructor with a specified field width and autoflush option
public FormattedWriter(Writer output, boolean autoflush, int width) {
this(output, autoflush, width, RIGHT
_
JUSTIFIED);
}
// Lots of overloaded print() and println() methods
// for basic data types...
}
How It Works
There are four fields in our
FormatWriter
class. We have defined two static constants that identify
whether the data is to be left or right justified in the output field. The justification member records this,
and it has the value
RIGHT
_
JUSTIFIED
by default. The variable,
width
, of type,
int
, holds the
output field width.
We have defined four constructors to provide flexibility in what you need to specify when you create an
object of type
FormattedWriter
. As a minimum, two arguments are required, a reference of type
Writer
to an object encapsulating the output stream, and the field width. You can optionally specify
the justification of the output in the field as one of the class constants we have defined for this purpose,
and a
boolean
value that determines whether autoflushing of the stream is to be applied. All the
constructors with fewer than four parameters call the constructor that has four by passing default values
for the unspecified parameters. Note that we only set the width if the value supplied is positive, and we
only set the justification if the argument is one or other of our constants. This ensures that our class
object is always initialized correctly.
Since we derive our class from
PrintWriter
, we have all the facilities of the
PrintWriter
class
available. At the moment, if you call
print()
or
println()
for a
FormatWriter
object, it will call
the base class method, so the behavior will be exactly the same as a
PrintWriter
object. To change
this, we will add our own
print()
and
println()
methods that override the base class methods.
First, we will add a helper method.
Overriding print() and println()
We know that if
width
is non-zero, we want to output
width
characters for each value that we write to
the stream. We need to figure out how many characters there are in each data value, subtract that from
the total field width, and add that many blanks to the beginning or the end of the string representing the
data value, depending on whether it is to be right or left justified. We can then write the resultant string
of characters to the stream. If the character representation of the data exceeds the field width, we can
output it as XXX...X with the number of X's corresponding to the specified
width
. This will show the
user that the value can be displayed within the specified width.