Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

2.8. Creating an Emphasized Header

2.8.1. Problem

You would like to print an attention-grabbing header.

2.8.2. Solution

Combine the powers of StringUtils.repeat() , StringUtils.center( ), and StringUtils.join( ) to create a textual header. The following example demonstrates the use of these three methods to create a header:

public String createHeader( String title ) {
    int width = 30;
    // Construct heading using StringUtils: repeat( ), center( ), and join( )
    String stars = StringUtils.repeat( "*", width);
    String centered = StringUtils.center( title, width, "*" );
    String heading = 
        StringUtils.join(new Object[]{stars, centered, stars}, "\n");
    return heading;
}

Here's the output of createHeader("TEST"):

******************************
************ TEST ************
******************************

2.8.3. Discussion

In the example, StringUtils.repeat( ) creates the top and bottom rows with StringUtils.repeat("*", 30), creating a string with 30 consecutive * characters. Calling StringUtils.center(title, width, "*") creates a middle line with the header title centered and surrounded by * characters. StringUtils.join() joins the lines together with the newline characters, and out pops a header.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.