Example usage for javax.swing JTable getColumnCount

List of usage examples for javax.swing JTable getColumnCount

Introduction

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

Prototype

@BeanProperty(bound = false)
public int getColumnCount() 

Source Link

Document

Returns the number of columns in the column model.

Usage

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Set the tab and return behavior for a table.
 *///from w w  w .  j a  v  a 2 s. co  m
private void setupTabReturnBehavior(final JTable table) {
    final InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

    // Have the enter key work the same as the tab key
    final KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    final KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    im.put(enter, im.get(tab));

    // Override the default tab behavior
    // Tab to the next editable cell. When no editable cells goto next cell.
    final Action oldTabAction = table.getActionMap().get(im.get(tab));
    final Action tabAction = new AbstractAction() {
        public void actionPerformed(final ActionEvent e) {
            if (null != oldTabAction) {
                oldTabAction.actionPerformed(e);
            }

            final JTable table = (JTable) e.getSource();
            final int rowCount = table.getRowCount();
            final int columnCount = table.getColumnCount();
            int row = table.getSelectedRow();
            int column = table.getSelectedColumn();

            // skip the no show when tabbing
            while (!table.isCellEditable(row, column) || table.getColumnClass(column) == Boolean.class) {
                column += 1;

                if (column == columnCount) {
                    column = 0;
                    row += 1;
                }

                if (row == rowCount) {
                    row = 0;
                }

                // Back to where we started, get out.
                if (row == table.getSelectedRow() && column == table.getSelectedColumn()) {
                    break;
                }
            }

            table.changeSelection(row, column, false, false);
        }
    };
    table.getActionMap().put(im.get(tab), tabAction);
}

From source file:de.mendelson.comm.as2.client.AS2Gui.java

/**
 * Scrolls to an entry of the passed table
 *
 * @param table Table to to scroll in/*from w  w  w . ja  v  a  2 s.  co m*/
 * @param row Row to ensure visibility
 */
private void makeRowVisible(JTable table, int row) {
    if (table.getColumnCount() == 0) {
        return;
    }
    if (row < 0 || row >= table.getRowCount()) {
        throw new IllegalArgumentException("Requested ensure visible of row " + String.valueOf(row)
                + ", table has only " + table.getRowCount() + " rows.");
    }
    Rectangle visible = table.getVisibleRect();
    Rectangle cell = table.getCellRect(row, 0, true);
    if (cell.y < visible.y) {
        visible.y = cell.y;
        table.scrollRectToVisible(visible);
    } else if (cell.y + cell.height > visible.y + visible.height) {
        visible.y = cell.y + cell.height - visible.height;
        table.scrollRectToVisible(visible);
    }
}

From source file:com.googlecode.vfsjfilechooser2.filepane.VFSFilePane.java

private void updateDetailsColumnModel(JTable table) {
    if (table != null) {
        // Install cell editor for editing file name
        if (!readOnly && (table.getColumnCount() > COLUMN_FILENAME)) {
            table.getColumnModel().getColumn(COLUMN_FILENAME).setCellEditor(getDetailsTableCellEditor());
        }//from   w  ww  .  ja v a2s. c  o  m
    }
}

From source file:edu.ucla.stat.SOCR.chart.Chart.java

public void updateExample(ChartExampleData example) {
    //  reset();/*from w  ww.j ava2 s .  co  m*/

    hasExample = true;
    JTable tempDataTable = example.getExample();

    /* if(tempDataTable.getRowCount()>dataTable.getRowCount())
    appendTableRows(tempDataTable.getRowCount()-dataTable.getRowCount());
       else   */
    resetTableRows(tempDataTable.getRowCount());

    for (int i = 0; i < tempDataTable.getColumnCount(); i++) {
        columnModel.getColumn(i).setHeaderValue(tempDataTable.getColumnName(i));
        //  System.out.println("updateExample tempDataTable["+i+"] = " +tempDataTable.getColumnName(i));
    }
    dTableHeader = new EditableHeader(columnModel);
    dataTable.setTableHeader(dTableHeader);

    for (int i = 0; i < tempDataTable.getRowCount(); i++)
        for (int j = 0; j < tempDataTable.getColumnCount(); j++) {
            dataTable.setValueAt(tempDataTable.getValueAt(i, j), i, j);
        }
    dataPanel.removeAll();
    JScrollPane tablePanel = new JScrollPane(dataTable);
    tablePanel.setRowHeaderView(headerTable);
    dataPanel.add(tablePanel);
    dataPanel.add(new JScrollPane(summaryPanel));
    dataTable.setGridColor(Color.gray);
    dataTable.setShowGrid(true);

    // this is a fix for the BAD SGI Java VM - not up to date as of dec. 22, 2003
    try {
        dataTable.setDragEnabled(true);
    } catch (Exception e) {
    }

    dataPanel.validate();
    //updateStatus("Example updated, please redo the mapping and update the chart");
}

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

/**
 * @param table/*from  w  w w  .  j  a va 2s  . c o m*/
 * @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:semaforo.Semaforo.java

public void formateaCabeceroWeeks(JTable table) {

    table.getColumnModel().getColumn(0).setHeaderRenderer(new ColumnHeaderRenderer());
    table.getColumnModel().getColumn(table.getColumnCount() - 1).setHeaderRenderer(new ColumnHeaderRenderer());

    for (int i = 1; i < table.getColumnCount() - 1; i++) {

        table.getColumnModel().getColumn(i)
                .setHeaderRenderer(new ColumnHeaderRenderer(new Color(240, 240, 120)));
    }/* w ww .  j a  v  a 2s.c om*/
}

From source file:library.Form_Library.java

License:asdf

public static void resizeColumnWidth(JTable table) {
    final TableColumnModel columnModel = table.getColumnModel();
    for (int column = 0; column < table.getColumnCount(); column++) {
        int width = 15; // Min width
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, column);
            Component comp = table.prepareRenderer(renderer, row, column);
            width = Math.max(comp.getPreferredSize().width + 1, width);
        }//  w w w  .  ja v a  2s .  c o m
        if (width > 300) {
            width = 300;
        }
        columnModel.getColumn(column).setPreferredWidth(width);
    }
}

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   w ww  .j ava 2s  .co 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 packTable(JTable table, int margin) {
    for (int colindex = 0; colindex < table.getColumnCount(); colindex++) {
        packColumn(table, colindex, margin);
    }/*from   w w  w  .  ja  v a  2  s .  c o  m*/
}

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

private void prepareTableForDragAndDrop(final JTable tbl) {
    tbl.setDragEnabled(true);//  w w  w  . j a  v a 2 s  .  co m
    tbl.setTransferHandler(new TransferHandler() {

        @Override
        public int getSourceActions(JComponent comp) {
            int result = NONE;
            if (comp == tbl)
                if (GenericObjectCollectController.this.getSelectedCollectable() != null)
                    result = COPY;
            return result;
        }

        @Override
        protected Transferable createTransferable(JComponent comp) {
            Transferable result = null;
            if (comp == tbl) {
                final int[] aiSelectedRows = tbl.getSelectedRows();

                final List<GenericObjectIdModuleProcess> lstgoimp = new ArrayList<GenericObjectIdModuleProcess>(
                        aiSelectedRows.length);
                for (int iSelectedRow : aiSelectedRows) {
                    final CollectableGenericObjectWithDependants clct = getResultTableModel()
                            .getCollectable(iSelectedRow);
                    GenericObjectIdModuleProcess transferableObject = getTransferableObject(tbl, iSelectedRow,
                            clct);
                    lstgoimp.add(transferableObject);
                }
                if (!lstgoimp.isEmpty())
                    result = new TransferableGenericObjects(lstgoimp);
            }
            return result;
        }

        private GenericObjectIdModuleProcess getTransferableObject(final JTable tbl, int iSelectedRow,
                final CollectableGenericObjectWithDependants clct) {
            return new GenericObjectIdModuleProcess(clct, getTreeViewIdentifier(clct),
                    getContents(tbl, iSelectedRow));
        }

        private String getContents(JTable tbl, int iRow) {
            final StringBuffer sb = new StringBuffer();
            final int iColumnCount = tbl.getColumnCount();

            for (int iColumn = 0; iColumn < iColumnCount; iColumn++) {
                final String sValue = tbl.getValueAt(iRow, iColumn).toString();
                if (sValue.indexOf("\n") >= 0 || sValue.indexOf("\t") >= 0) {
                    sb.append("\"");
                    sb.append(sValue.replaceAll("\"", "\"\""));
                    sb.append("\"");
                } else {
                    sb.append(sValue);
                }
                if (iColumn < iColumnCount - 1)
                    sb.append("\t");
            }
            return sb.toString();
        }
    });
}