- Forward


Centering
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back Forward
  • The Idea:
    • Many programs need to center content of some kind in a container of some kind
  • An Example:
    • Text within a line (so it needs to find the column in where the text should start)
Review
Back Forward
  • A Limitation of Console Output:
    • You can't specify the column
  • A Work-Around:
    • Create a String that has the appropriate number of spaces before the text
Thinking About the Problem
Back Forward
  • A Specific Example:
    • The line is 9 characters wide and 0-based
    • The text is 5 characters wide and 0-based
  • Some Implications:
    • The middle character in the line has index 4
    • The middle character of the text has index 2
  • A Solution to this Specific Example:
    • Character 2 of the text has to be at position 4 of the line, meaning character 0 of the text must be at position 2 of the line (i.e., there must be two leading spaces)
The Pattern
Back Forward
  • Notation:
    • \(C\) denotes the container (a generalization of the line)
    • \(c\) denotes the content (a generalization of the text)
    • \(E\) denotes the extent (a generalization of the width)
    • \(M\) denotes the mid-point
    • \(R\) denotes the reference (a generalization of the starting character)
  • The Equations (for Each Dimension):
    • \(C^M = C^R + (C^E / 2)\)
    • \(c^M = (c^E / 2)\)
    • \(c^R = c^M - (c^E / 2)\)
The Pattern (cont.)
Back Forward

In One Dimension

javaexamples/programmingpatterns/Centering.java (Fragment: one)
 
The Pattern (cont.)
Back Forward

In Multiple Dimensions

javaexamples/programmingpatterns/Centering.java (Fragment: multi)
 
Examples
Back Forward

In One Dimension

images/Centering_1D.svg
Examples (cont.)
Back Forward

In Two Dimensions

images/Centering_2D.svg
Some Warnings
Back Forward
  • Coordinate Systems:
    • These examples use Euclidean coordinates but computer displays use screen coordinates
  • Discrete Sets:
    • If the content/container are discrete (i.e., use integer sizes and positions) then the content may have to "lean" to the left or right
  • Clipping:
    • The container may not be large enough to hold the content in which case it may need to be clipped
There's Always More to Learn
Back -