Tag Archives: Navigation

Walking Views

Introduction

A very important part of the Swing text package is the View class. As the name suggests it represents a view of the text model, or a piece of the text model. It is this class that is responsible for the look of the text component. The view is not intended to be some completely new thing that one must learn, but rather is much like a lightweight component.

By default, a view is very light. It contains a reference to the parent view from which it can fetch many things without holding state, and it contains a reference to a portion of the model (Element). A view does not have to exactly represent an element in the model, that is simply a typical and therefore convenient mapping. A view can alternatively maintain a couple of Position objects to maintain its location in the model (i.e. represent a fragment of an element). This is typically the result of formatting where views have been broken down into pieces. The convenience of a substantial relationship to the element makes it easier to build factories to produce the views, and makes it easier to keep track of the view pieces as the model is changed and the view must be changed to reflect the model. Simple views therefore represent an Element directly and complex views do not.

This example shows you how to navigate trough the hierarchy of views.

// Create a text component
JTextComponent textComp = new JTextPane();

// Get the root view
View v = textComp.getUI().getRootView(textComp);

// Walk the view hierarchy
walkView(v, 0);
// Recursively walks a view hierarchy
public void walkView(View view, int level) {
    // Process view...

    // Get number of children views
    int n = view.getViewCount();

    // Visit the children of this view
    for (int i=0; i<n; i++) {
        walkView(view.getView(i), level+1);
     }
}