Sample Code Sample Code: Align Column Values


private final Object[][] columnHeaderConfig = {
    // Column key and column width in characters units
    {"My Column 1", new Integer(20)},    // First column, left-aligned
    {"My Column 2", new Integer(10013)}, // Second column, center-aligned
    {"My Column 3", new Integer(20015)}, // Third column, right-aligned
    ...
};

int nCols = columnHeaderConfig.length;
String[][] columnHeaders = new String[nCols][3];

// Get FontMetrics for header. Since we don't have access to the
// header component, create a dummy component that uses the same
// font as the header. Then get the FontMetrics for the dummy
// component.
//
JLabel dummy = new JLabel();
dummy.setFont(ResourceManager.labelFont);
FontMetrics fmHeader = dummy.getFontMetrics(ResourceManager.labelFont);

// Do the same to get FontMetrics for the data
//
dummy.setFont(ResourceManager.bodyFont);
FontMetrics fmData = dummy.getFontMetrics(ResourceManager.labelFont);
for (int i = 0; i < nCols; i++) {
    // Get actual header string
    columnHeaders[i][0] = (String)columnHeaderConfig[i][0];

    // First compute the width of the localized column header.
    // Note that this includes a 2-character margin on each
    // side, based on the character 'A'.
    //
    int headerWidth = fmHeader.stringWidth(columnHeaders[i][0]);
    headerWidth += fmHeader.stringWidth("AAAA");

    // Extract the alignment value from the column width:
    // width values > 20000 -> right aligned
    // width values > 10000 -> center aligned
    // width values > 0     -> left aligned
    //
    int columnWidth = ((Integer)columnHeaderConfig[i][1]).intValue();
    int alignmentValue = 0;
    if (columnWidth > 20000) {
        alignmentValue = 20000;
    } else if (columnWidth > 10000) {
        alignmentValue = 10000;
    }
    columnWidth -= alignmentValue;

    // Then compute the preferred width of the column's data.  This too,
    // is based on the character 'A'.
    //
    int dataWidth = fmData.stringWidth("A");
    dataWidth *= columnWidth;
    dataWidth += alignmentValue;

    // Actual width is max of header/data width, but in String format.
    columnHeaders[i][1] = new String(
        String.valueOf(Math.max(headerWidth, dataWidth)));
}

...

// The columnHeaders object array can then be set on a VScopeNode,
// whether it is the internal root for your data model, or a node
// in the navigation pane.
node.setColumnHeaders(columnHeaders);