Example usage for javax.swing.table TableCellRenderer getTableCellRendererComponent

List of usage examples for javax.swing.table TableCellRenderer getTableCellRendererComponent

Introduction

In this page you can find the example usage for javax.swing.table TableCellRenderer getTableCellRendererComponent.

Prototype

Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column);

Source Link

Document

Returns the component used for drawing the cell.

Usage

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * @param table/*w w w .ja v a2  s  .com*/
 * @param model
 * @return
 */
public static JTable autoResizeColWidth(final JTable table, final DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();

    int preferredWidthTotal = 0;
    int renderedWidthTotal = 0;
    int[] colWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();

        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0,
                0);

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                    r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        preferredWidthTotal += col.getPreferredWidth();
        colWidths[i] = width;

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            colModel.getColumn(i).setPreferredWidth(colWidths[i]);
        }
    }

    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    table.getTableHeader().setReorderingAllowed(false);

    return table;
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Calculates and sets the each column to it preferred size.  NOTE: This
 * method also sets the table height to 10 rows.
 * /*from  w w  w  .  j a v a2  s.c  o  m*/
 * @param table the table to fix up
 * @param numRowsHeight the number of rows to make the table height (or null not to set it)
 */
public static void calcColumnWidths(final JTable table, final Integer numRowsHeight, final Integer maxWidth) {
    if (table != null) {
        JTableHeader header = table.getTableHeader();

        TableCellRenderer defaultHeaderRenderer = null;

        if (header != null) {
            defaultHeaderRenderer = header.getDefaultRenderer();
        }

        TableColumnModel columns = table.getColumnModel();
        TableModel data = table.getModel();

        int margin = columns.getColumnMargin(); // only JDK1.3

        int rowCount = data.getRowCount();

        int totalWidth = 0;

        for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
            TableColumn column = columns.getColumn(i);

            int columnIndex = column.getModelIndex();

            int width = -1;

            TableCellRenderer h = column.getHeaderRenderer();

            if (h == null)
                h = defaultHeaderRenderer;

            if (h != null) // Not explicitly impossible
            {
                Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1,
                        i);

                width = c.getPreferredSize().width;
            }

            for (int row = rowCount - 1; row >= 0; --row) {
                TableCellRenderer r = table.getCellRenderer(row, i);

                Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false,
                        false, row, i);

                width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer

                if (maxWidth != null) {
                    width = Math.min(width, maxWidth);
                }
            }

            if (width >= 0) {
                column.setPreferredWidth(width + margin); // <1.3: without margin
            } else {
                // ???
            }

            totalWidth += column.getPreferredWidth();
        }

        // If you like; This does not make sense for two many columns!
        Dimension size = table.getPreferredScrollableViewportSize();
        //if (totalWidth > size.width)
        {
            if (numRowsHeight != null) {
                size.height = Math.min(size.height, table.getRowHeight() * numRowsHeight);
            }
            size.width = totalWidth;
            table.setPreferredScrollableViewportSize(size);
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.java

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 *///  ww  w . j a  v a 2  s  . c  o  m
private void initColumnSizes(final JTable tableArg) {
    ColTableModel tblModel = (ColTableModel) tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    TableCellRenderer headerRenderer = tableArg.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < tblModel.getColumnCount(); i++) {
        column = tableArg.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        /*
        if (DEBUG) {
        System.out.println("Initializing width of column "
                           + i + ". "
                           + "headerWidth = " + headerWidth
                           + "; cellWidth = " + cellWidth);
        }*/

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 *//*from ww  w.  ja v a2s .  c o  m*/
private void initColumnSizes(final JTable tableArg, final JButton theSaveBtn) throws Exception {
    TableModel tblModel = tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    Element uploadDefs = null;
    if (WorkbenchTask.isCustomizedSchema()) {
        uploadDefs = XMLHelper.readFileToDOM4J(
                new File(UIRegistry.getAppDataDir() + File.separator + "specify_workbench_upload_def.xml"));
    } else {
        uploadDefs = XMLHelper.readDOMFromConfigDir("specify_workbench_upload_def.xml");
    }

    //UIRegistry.getInstance().hookUpUndoableEditListener(cellEditor);

    Vector<WorkbenchTemplateMappingItem> wbtmis = new Vector<WorkbenchTemplateMappingItem>();
    wbtmis.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(wbtmis);

    DBTableIdMgr databaseSchema = WorkbenchTask.getDatabaseSchema();

    columnMaxWidths = new Integer[tableArg.getColumnCount()];
    for (int i = 0; i < wbtmis.size() /*tableArg.getColumnCount()*/; i++) {
        TableCellRenderer headerRenderer = tableArg.getColumnModel().getColumn(i).getHeaderRenderer();
        WorkbenchTemplateMappingItem wbtmi = wbtmis.elementAt(i);

        // Now go retrieve the data length
        int fieldWidth = WorkbenchDataItem.getMaxWBCellLength();
        DBTableInfo ti = databaseSchema.getInfoById(wbtmi.getSrcTableId());
        if (ti != null) {
            DBFieldInfo fi = ti.getFieldByName(wbtmi.getFieldName());
            if (fi != null) {
                wbtmi.setFieldInfo(fi);
                //System.out.println(fi.getName()+"  "+fi.getLength()+"  "+fi.getType());
                if (RecordTypeCodeBuilder.getTypeCode(fi) == null && fi.getLength() > 0) {
                    fieldWidth = Math.min(fi.getLength(), WorkbenchDataItem.getMaxWBCellLength());
                }
            } else {
                log.error("Can't find field with name [" + wbtmi.getFieldName() + "]");
            }
        } else {
            log.error("Can't find table [" + wbtmi.getSrcTableId() + "]");
        }
        columnMaxWidths[i] = new Integer(fieldWidth);
        GridCellEditor cellEditor = getCellEditor(wbtmi, fieldWidth, theSaveBtn, uploadDefs);
        column = tableArg.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        //comp.setBackground(Color.WHITE);

        int maxWidth = headerWidth + 10;
        TableModel m = tableArg.getModel();
        FontMetrics fm = comp.getFontMetrics(comp.getFont());
        for (int row = 0; row < tableArg.getModel().getRowCount(); row++) {
            String text = m.getValueAt(row, i).toString();
            maxWidth = Math.max(maxWidth, fm.stringWidth(text) + 10);
            //log.debug(i+" "+maxWidth);
        }

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        //log.debug(Math.max(maxWidth, cellWidth));
        //log.debug(Math.min(Math.max(maxWidth, cellWidth), 400));
        column.setPreferredWidth(Math.min(Math.max(maxWidth, cellWidth), 400));

        column.setCellEditor(cellEditor);
    }
    //tableArg.setCellEditor(cellEditor);
}

From source file:op.tools.SYSTools.java

public static void packColumn(JTable table, int vColIndex, int margin) {
    TableModel model = table.getModel();
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // Get width of column header
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
        renderer = table.getTableHeader().getDefaultRenderer();
    }/*w  ww .  j  a  v  a 2  s.  c  om*/
    Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
    width = comp.getPreferredSize().width;

    // Get maximum width of column data
    for (int r = 0; r < table.getRowCount(); r++) {
        renderer = table.getCellRenderer(r, vColIndex);
        comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false, r,
                vColIndex);
        width = Math.max(width, comp.getPreferredSize().width);
    }

    // Add margin
    width += 2 * margin;
    // Set the width
    col.setPreferredWidth(width);

    OPDE.debug("packColumn/3: col=" + vColIndex + "  width=" + width);
}

From source file:org.apache.cayenne.swing.TableBinding.java

protected void resizeColumns(Object[] sampleLongValues) {

    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
    TableColumnModel columnModel = table.getColumnModel();
    TableModel tableModel = table.getModel();

    for (int i = 0; i < columnModel.getColumnCount(); i++) {

        TableColumn column = columnModel.getColumn(i);

        Component header = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false,
                false, 0, 0);//from  ww w.  j a  va 2  s.  co  m
        int headerWidth = header.getPreferredSize().width;

        if (sampleLongValues[i] != null) {
            Component bigCell = table.getDefaultRenderer(tableModel.getColumnClass(i))
                    .getTableCellRendererComponent(table, sampleLongValues[i], false, false, 0, i);
            int cellWidth = bigCell.getPreferredSize().width;
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        } else {
            column.setPreferredWidth(headerWidth);
        }
    }
}

From source file:org.lockss.devtools.plugindef.EDPInspectorTableModel.java

public void setColumnSize(JTable table, int col) {
    TableColumn column = null;/*from www .  j  a va  2  s  .  c o  m*/
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    String longestStr = "";
    String curString = "";

    for (int row = 0; row < inspectorEntries.length; row++) {
        curString = data[row][col].toString();
        if (curString.length() > longestStr.length()) {
            longestStr = curString;
        }
    }
    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();

    column = table.getColumnModel().getColumn(col);

    comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;

    comp = table.getDefaultRenderer(getColumnClass(col)).getTableCellRendererComponent(table, longestStr, false,
            false, 0, col);
    cellWidth = comp.getPreferredSize().width;

    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}

From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java

/**
 * sets up a modified renderer for the result table header that uses the HTML formatted toString() value of the
 * column's entity field rather than its unformatted getLabel() value.
 *///from w ww .ja v  a  2s. com
private void setupResultTableHeaderRenderer() {
    final JTableHeader header = getResultTable().getTableHeader();
    final TableCellRenderer headerrendererDefault = header.getDefaultRenderer();
    header.setDefaultRenderer(new TableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable tbl, Object oValue, boolean bSelected,
                boolean bHasFocus, int iRow, int iColumn) {
            final CollectableEntityField f = GenericObjectCollectController.this.getResultTableModel()
                    .getCollectableEntityField(tbl.convertColumnIndexToModel(iColumn));
            final String value;
            if (f instanceof CollectableEOEntityField) {
                // In the pivot case, we want to separate the column name
                // from the tool top.
                final CollectableEOEntityField field = (CollectableEOEntityField) f;
                final EntityFieldMetaDataVO ef = field.getMeta();
                if (ef.getPivotInfo() != null) {
                    value = ef.getField() + ":" + ef.getPivotInfo().getValueField();
                } else {
                    value = f.getLabel();
                }
            } else {
                value = f.getLabel();
            }
            return headerrendererDefault.getTableCellRendererComponent(tbl, value, bSelected, bHasFocus, iRow,
                    iColumn);
        }
    });
}

From source file:org.opendatakit.briefcase.ui.FormTransferTable.java

public FormTransferTable(JButton btnSelectOrClearAllForms, FormStatus.TransferType transferType,
        JButton btnTransfer) {//from   ww w  .ja va 2  s .c  o  m
    super(new FormTransferTableModel(btnSelectOrClearAllForms, transferType, btnTransfer));
    AnnotationProcessor.process(this);// if not using AOP
    // set the button column renderer to a custom renderer
    getColumn(getColumnName(FormTransferTableModel.BUTTON_COLUMN)).setCellRenderer(new JTableButtonRenderer());
    addMouseListener(new JTableButtonMouseListener());

    TableColumnModel columns = this.getColumnModel();
    // determine width of "Selected" column header
    TableCellRenderer headerRenderer = this.getTableHeader().getDefaultRenderer();
    Component comp = headerRenderer.getTableCellRendererComponent(null, columns.getColumn(0).getHeaderValue(),
            false, false, 0, 0);
    int headerWidth = comp.getPreferredSize().width;
    columns.getColumn(0).setMinWidth(headerWidth);
    columns.getColumn(0).setMaxWidth(headerWidth);
    columns.getColumn(0).setPreferredWidth(headerWidth);

    // create a detail button (that we'll throw away)
    // so we can get the needed column and row dimensions.
    comp = new DetailButton(null);
    int buttonWidth = comp.getPreferredSize().width;
    int buttonHeight = comp.getPreferredSize().height;
    columns.getColumn(FormTransferTableModel.BUTTON_COLUMN).setMinWidth(buttonWidth);
    columns.getColumn(FormTransferTableModel.BUTTON_COLUMN).setMaxWidth(buttonWidth);
    columns.getColumn(FormTransferTableModel.BUTTON_COLUMN).setPreferredWidth(buttonWidth);

    // set the row height to be big enough to include a button and have space above and below it
    setRowHeight(buttonHeight); // btn used is arbitrary...

    // and scale the others to be wider...
    columns.getColumn(1).setPreferredWidth(5 * headerWidth);
    columns.getColumn(2).setPreferredWidth(5 * headerWidth);
    this.setFillsViewportHeight(true);
}

From source file:org.springframework.richclient.table.renderer.BeanTableCellRenderer.java

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    if (value != null) {
        if (beanWrapper == null) {
            beanWrapper = new BeanWrapperImpl(value);
        } else {//w  ww .j  av a  2  s .  co  m
            beanWrapper.setWrappedInstance(value);
        }
        try {
            BeanInfo info = Introspector.getBeanInfo(value.getClass());
            int index = info.getDefaultPropertyIndex();
            if (index != -1) {
                String defaultPropName = beanWrapper.getPropertyDescriptors()[index].getName();
                Object val = beanWrapper.getPropertyValue(defaultPropName);
                TableCellRenderer r = table.getDefaultRenderer(val.getClass());
                return r.getTableCellRendererComponent(table, val, isSelected, hasFocus, row, column);
            }
        } catch (IntrospectionException e) {
            log.debug("Error during introspection of bean: " + e.getMessage(), e);
        }
    }
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}