Example usage for javax.swing JTable getDefaultRenderer

List of usage examples for javax.swing JTable getDefaultRenderer

Introduction

In this page you can find the example usage for javax.swing JTable getDefaultRenderer.

Prototype

public TableCellRenderer getDefaultRenderer(Class<?> columnClass) 

Source Link

Document

Returns the cell renderer to be used when no renderer has been set in a TableColumn.

Usage

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

/**
 * Sets a JTable to have the headers be centered. Also, the caller can indicate whether
 * and "String" columns are also centered.
 * @param table the table/*from   w  w  w .jav a2 s .  c om*/
 * @param dataColsAlso whether the String data columns should be cetnered.
 */
public static void makeTableHeadersCentered(final JTable table, final boolean dataColsAlso) {
    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.CENTER);

    if (dataColsAlso) {
        TableCellRenderer tcr = table.getDefaultRenderer(String.class);

        // For Strings with no changes made to the table, the render is a DefaultTableCellRender.
        DefaultTableCellRenderer dtcr = (DefaultTableCellRenderer) tcr;

        // set the alignment to center
        dtcr.setHorizontalAlignment(SwingConstants.CENTER);
    }
}

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
 *///from  w w  w  .  ja v a  2s . c om
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:com.vgi.mafscaling.ClosedLoop.java

private JTable createAfrDataTable(JPanel panel, String tableName, int gridy) {
    final JTable afrTable = new JTable() {
        private static final long serialVersionUID = 6526901361175099297L;

        public boolean isCellEditable(int row, int column) {
            return false;
        };/*  ww w .  j  a v  a2  s  .co  m*/
    };
    DefaultTableColumnModel afrModel = new DefaultTableColumnModel();
    final TableColumn afrColumn = new TableColumn(0, 250);
    afrColumn.setHeaderValue(tableName);
    afrModel.addColumn(afrColumn);
    JTableHeader lblAfrTableName = afrTable.getTableHeader();
    lblAfrTableName.setColumnModel(afrModel);
    lblAfrTableName.setReorderingAllowed(false);
    DefaultTableCellRenderer headerRenderer = (DefaultTableCellRenderer) lblAfrTableName.getDefaultRenderer();
    headerRenderer.setHorizontalAlignment(SwingConstants.LEFT);

    GridBagConstraints gbc_lblAfrTableName = new GridBagConstraints();
    gbc_lblAfrTableName.insets = new Insets((gridy == 0 ? 0 : 5), 0, 0, 0);
    gbc_lblAfrTableName.anchor = GridBagConstraints.PAGE_START;
    gbc_lblAfrTableName.fill = GridBagConstraints.HORIZONTAL;
    gbc_lblAfrTableName.gridx = 0;
    gbc_lblAfrTableName.gridy = gridy;
    panel.add(lblAfrTableName, gbc_lblAfrTableName);

    afrTable.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            afrColumn.setWidth(afrTable.getWidth());
        }
    });
    afrTable.getTableHeader().setReorderingAllowed(false);
    afrTable.setColumnSelectionAllowed(true);
    afrTable.setCellSelectionEnabled(true);
    afrTable.setBorder(new LineBorder(new Color(0, 0, 0)));
    afrTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    afrTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    afrTable.setModel(new DefaultTableModel(AfrTableRowCount, AfrTableColumnCount));
    Utils.initializeTable(afrTable, ColumnWidth);

    if (tableName.equals(Afr1TableName)) {
        Format[][] formatMatrix = { { new DecimalFormat("#"), new DecimalFormat("0.00") } };
        NumberFormatRenderer renderer = (NumberFormatRenderer) afrTable.getDefaultRenderer(Object.class);
        renderer.setFormats(formatMatrix);
    } else if (tableName.equals(Afr2TableName)) {
        Format[][] formatMatrix = { { new DecimalFormat("#"), new DecimalFormat("0.00") },
                { new DecimalFormat("#"), new DecimalFormat("#") } };
        NumberFormatRenderer renderer = (NumberFormatRenderer) afrTable.getDefaultRenderer(Object.class);
        renderer.setFormats(formatMatrix);
    }

    GridBagConstraints gbc_afrTable = new GridBagConstraints();
    gbc_afrTable.insets = new Insets(0, 0, 0, 0);
    gbc_afrTable.anchor = GridBagConstraints.PAGE_START;
    gbc_afrTable.gridx = 0;
    gbc_afrTable.gridy = gridy + 1;
    panel.add(afrTable, gbc_afrTable);

    excelAdapter.addTable(afrTable, true, false);

    return afrTable;
}

From source file:semaforo.Semaforo.java

public void loadTableCells(JTable TableWeek, int index, Map<String, List<Integer>> ht, int tamano) {
    System.out.println("---------------------------->" + TableWeek.getName());
    Settings settings = Controller.getSettings();

    for (int i = 0; i < tamano - 1; i++) {
        TableWeek.getColumnModel().getColumn(i)
                .setCellRenderer(new ResetCellRenderer(TableWeek.getDefaultRenderer(Object.class),
                        Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY, i));
    }//from w  w  w.j a  va  2s  .  c o  m

    int[] my_positions = new int[num_positions];
    boolean[] paint = new boolean[num_positions];

    for (int j = 0; j < num_positions; j++) {
        my_positions[j] = -1;
        paint[j] = false;
    }

    //int num = settings.getTickers().size();
    // if (TableWeek.getModel().getRowCount() > 0) {
    int num = Math.min(settings.getTickers().size(), TableWeek.getModel().getRowCount());
    //   }

    // synchronized (Controller.positionLock) {
    for (int row = 0; row < num; row++) {

        if (ht.get(TableTicker.getValueAt(row, 0)) != null) {
            //                if(row>24)JOptionPane.showMessageDialog(null, row+"");
            List<Integer> listInt = ht
                    .get(TableTicker.getValueAt(row, 0) /*settings.getTickers().get(row).getName()*/);
            my_positions[row] = -1;
            if (!listInt.isEmpty() && settings.getTickers().get(row).isHistory()) {
                //                    int col = ht.get(TableTicker.getValueAt(row, 0)).get(index) + 1;
                int col = ht.get(TableTicker.getValueAt(row, 0)).get(index);
                my_positions[row] = col;
            }

        }
    }

    // }
    //Modify the cell
    // if (num > 0) {
    for (int col = 0; col < tamano/*settings.getTickers().size()*/; col++) {

        //     if (paint[col]) {
        TableWeek.getColumnModel().getColumn(col).setCellRenderer(
                new MyCellRenderer(TableWeek.getDefaultRenderer(Object.class), index, Color.LIGHT_GRAY,
                        Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY, my_positions, col));
        //     }

    }
    //  }
}

From source file:semaforo.Semaforo.java

public synchronized void loadTableWeek(JTable TableWeek, int index) {
    Settings settings = Controller.getSettings();

    //TableWeek.getColumnModel().getColumn(0).setPreferredWidth(350); //150
    TableWeek.setRowHeight(20); //40
    //TableWeek.getColumnModel().getColumn(9).setPreferredWidth(350);//150
    TableWeek.setFont(new Font("Arial", Font.BOLD, 12));//18

    CustomRenderer cr = new CustomRenderer(TableWeek.getDefaultRenderer(Object.class), Color.LIGHT_GRAY,
            Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY);
    TableWeek.setDefaultRenderer(Object.class, cr);
    DefaultTableModel model = (DefaultTableModel) TableWeek.getModel();
    Object[] o = new Object[10];

    JTableHeader header = TableWeek.getTableHeader();
    header.setPreferredSize(new Dimension(10, 30)); //100
    TableWeek.getTableHeader().setFont(new Font("Arial", Font.BOLD, 15));

    /* DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
     centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
     TableWeek.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
     TableWeek.getColumnModel().getColumn(9).setCellRenderer(centerRenderer);
     TableWeek.setDefaultRenderer(String.class, centerRenderer);*/
    int num = settings.getTickers().size();

    /*   while(DDBB.loadData) {
     try {/*  w  w  w.j  av a2s.c  om*/
     Thread.sleep(500);
     } catch (InterruptedException ex) {
     Logger.getLogger(Semaforo.class.getName()).log(Level.SEVERE, null, ex);
     }
     }*/
    if (TableWeek.getModel().getRowCount() > 0) {
        num = Math.min(settings.getTickers().size(), TableWeek.getModel().getRowCount());
    }

    for (int i = 0; i < num; i++) {
        o[0] = settings.getTickers().get(i).getMinValue(index);
        o[9] = settings.getTickers().get(i).getMaxValue(index);
        model.addRow(o);
    }
}

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
 *///  www . j ava  2s. com
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:org.drugis.addis.gui.components.EnhancedTable.java

public static void insertEntityRenderer(JTable table) {
    final TableCellRenderer defaultRenderer = table.getDefaultRenderer(Object.class);
    EntityRenderer renderer = new EntityRenderer(defaultRenderer);
    table.setDefaultRenderer(Object.class, renderer);
    // Entity is an interface, and if something returns a sub-interface of Entity, that is not a sub-type of Object
    // Hence, we have to attach the renderer to Entity.class as well.
    table.setDefaultRenderer(Entity.class, renderer);
}

From source file:org.drugis.addis.gui.renderer.EntityCellRenderer.java

public static void insertEntityRenderer(JTable table) {
    final TableCellRenderer defaultRenderer = table.getDefaultRenderer(Object.class);
    EntityCellRenderer renderer = new EntityCellRenderer(defaultRenderer);
    table.setDefaultRenderer(Object.class, renderer);
    // Entity is an interface, and if something returns a sub-interface of Entity, that is not a sub-type of Object
    // Hence, we have to attach the renderer to Entity.class as well.
    table.setDefaultRenderer(Entity.class, renderer);
}

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

public void setColumnSize(JTable table, int col) {
    TableColumn column = null;// w w w  .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.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 {/*from   www.j av  a2 s . c om*/
            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);
}