Example usage for javax.swing.table TableModel getColumnClass

List of usage examples for javax.swing.table TableModel getColumnClass

Introduction

In this page you can find the example usage for javax.swing.table TableModel getColumnClass.

Prototype

public Class<?> getColumnClass(int columnIndex);

Source Link

Document

Returns the most specific superclass for all the cell values in the column.

Usage

From source file:org.yccheok.jstock.file.Statements.java

/**
 * Construct Statements based on given TableModel.
 *
 * @param tableModel given TableModel//from  w  w w.jav a  2s  .c o  m
 * @return the constructed Statements. UNKNOWN_STATEMENTS if fail
 */
public static Statements newInstanceFromTableModel(TableModel tableModel, boolean languageIndependent) {
    final CSVHelper csvHelper = (CSVHelper) tableModel;
    final GUIBundleWrapper guiBundleWrapper = GUIBundleWrapper.newInstance(
            languageIndependent ? GUIBundleWrapper.Language.INDEPENDENT : GUIBundleWrapper.Language.DEFAULT);

    final int column = tableModel.getColumnCount();
    final int row = tableModel.getRowCount();

    List<String> strings = new ArrayList<String>();
    for (int i = 0; i < column; i++) {
        final String type = languageIndependent ? csvHelper.getLanguageIndependentColumnName(i)
                : tableModel.getColumnName(i);
        final Class c = tableModel.getColumnClass(i);
        if (c.equals(Stock.class)) {
            final String code_string = guiBundleWrapper.getString("MainFrame_Code");
            final String symbol_string = guiBundleWrapper.getString("MainFrame_Symbol");
            strings.add(code_string);
            strings.add(symbol_string);
        }
        if (c.equals(StockInfo.class)) {
            final String code_string = guiBundleWrapper.getString("MainFrame_Code");
            final String symbol_string = guiBundleWrapper.getString("MainFrame_Symbol");
            strings.add(code_string);
            strings.add(symbol_string);
        } else {
            strings.add(type);
        }

    }

    // Comment handling.
    CommentableContainer commentableContainer = null;
    if (tableModel instanceof CommentableContainer) {
        commentableContainer = (CommentableContainer) tableModel;
    }

    Statement.What what = Statement.what(strings);
    final Statements s = new Statements(what.type, what.guiBundleWrapper);

    for (int i = 0; i < row; i++) {
        final List<Atom> atoms = new ArrayList<Atom>();
        for (int j = 0; j < column; j++) {
            final String type = languageIndependent ? csvHelper.getLanguageIndependentColumnName(j)
                    : tableModel.getColumnName(j);
            final Object object = tableModel.getValueAt(i, j);
            final Class c = tableModel.getColumnClass(j);
            if (c.equals(Stock.class)) {
                final Stock stock = (Stock) object;
                // There are no way to represent Stock in text form. We
                // will represent them in Code and Symbol.
                // Code first. Follow by symbol.

                final String code_string = guiBundleWrapper.getString("MainFrame_Code");
                final String symbol_string = guiBundleWrapper.getString("MainFrame_Symbol");

                atoms.add(new Atom(stock.code.toString(), code_string));
                atoms.add(new Atom(stock.symbol.toString(), symbol_string));
            } else if (c.equals(StockInfo.class)) {
                final StockInfo stockInfo = (StockInfo) object;

                final String code_string = guiBundleWrapper.getString("MainFrame_Code");
                final String symbol_string = guiBundleWrapper.getString("MainFrame_Symbol");

                atoms.add(new Atom(stockInfo.code.toString(), code_string));
                atoms.add(new Atom(stockInfo.symbol.toString(), symbol_string));
            } else if (c.equals(Date.class)) {
                atoms.add(new Atom(object != null
                        ? org.yccheok.jstock.gui.Utils.commonDateFormat(((Date) object).getTime())
                        : "", type));
            } else {
                // For fall below and rise above, null value is permitted.
                // Use empty string to represent null value.
                atoms.add(new Atom(object != null ? object : "", type));
            }
        }

        // Comment handling.
        if (commentableContainer != null) {
            atoms.add(new Atom(commentableContainer.getCommentable(i).getComment(),
                    guiBundleWrapper.getString("PortfolioManagementJPanel_Comment")));
        }

        final Statement statement = new Statement(atoms);

        if (s.getType() != statement.getType()) {
            // Doesn't not match. Return UNKNOWN_STATEMENTS to indicate we fail to
            // construct Statements from TableModel.
            return UNKNOWN_STATEMENTS;
        }

        s.statements.add(statement);
    }

    // Any metadata? This is special hack since Android introduction.
    if (tableModel instanceof StockTableModel) {
        s.metadatas.put("timestamp", Long.toString(((StockTableModel) tableModel).getTimestamp()));
    }

    return s;
}

From source file:org.yccheok.jstock.gui.JTableUtilities.java

public static void insertTableColumnFromModel(JTable jTable, Object value, int clickedColumnIndex) {
    boolean isVisible = true;

    try {/*  w w w .  j a  va  2s. c o  m*/

        TableColumn tableColumn = jTable.getColumn(value);

    }

    catch (java.lang.IllegalArgumentException exp) {

        isVisible = false;

    }

    if (isVisible)
        return;

    TableModel tableModel = jTable.getModel();

    final int modelIndex = getModelColumnIndex(jTable, value);

    Class c = tableModel.getColumnClass(modelIndex);

    TableColumn tableColumn = new javax.swing.table.TableColumn(modelIndex, 0, jTable.getDefaultRenderer(c),
            jTable.getDefaultEditor(c));

    jTable.addColumn(tableColumn);

    makeTableColumnWidthFit(jTable, jTable.getColumnCount() - 1, 5);

    // If we right clicked on the 3rd column, and select a new column, we
    // would like the new column to be inserted into 4th column. Note that,
    // clickedColumnIndex will be < 0, if we right clicked on empty area.
    if (clickedColumnIndex < 0) {
        // Have it in the last column when we right clicked on empty area.
        jTable.moveColumn(jTable.getColumnCount() - 1, jTable.getColumnCount() - 1);
    } else {
        // +1, as we want our newly inserted column to be at the right of
        // clicked column.
        jTable.moveColumn(jTable.getColumnCount() - 1,
                Math.min(jTable.getColumnCount() - 1, clickedColumnIndex + 1));
    }
}

From source file:org.yccheok.jstock.gui.portfolio.DividendSummaryJDialog.java

/** Creates new form DividendSummaryJDialog */
public DividendSummaryJDialog(java.awt.Frame parent, boolean modal, DividendSummary dividendSummary,
        PortfolioManagementJPanel portfolioManagementJPanel) {
    super(parent, modal);
    this.portfolioManagementJPanel = portfolioManagementJPanel;
    // Clone another copy to avoid original copy from being corrupted.
    this.dividendSummary = new DividendSummary(dividendSummary);
    this.dividendSummaryAfterPressingOK = null;
    initComponents();//from  w w  w  . ja v  a2  s  .  c  om

    // Hackish way to make Mac works.
    pack();
    setSize(new java.awt.Dimension(339, 373));
    setLocationRelativeTo(null);

    ((TableRowSorter) this.jTable1.getRowSorter()).setStringConverter(new TableStringConverter() {

        @Override
        public String toString(TableModel model, int row, int column) {
            if (model.getColumnClass(column) == StockInfo.class) {
                return ((StockInfo) model.getValueAt(row, column)).symbol.toString();
            }

            return model.getValueAt(row, column).toString();
        }
    });

    // Sort by date, with latest comes first.
    final RowSorter<? extends TableModel> rowSorter = this.jTable1.getRowSorter();
    if (rowSorter != null) {
        rowSorter.toggleSortOrder(0);
        final List<? extends SortKey> sortKeys = rowSorter.getSortKeys();
        if (sortKeys.size() > 0) {
            if (sortKeys.get(0).getSortOrder() != javax.swing.SortOrder.DESCENDING) {
                rowSorter.toggleSortOrder(0);
            }
        }
    }

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {
            AutoDividendTask autoDividendTask = DividendSummaryJDialog.this.autoDividendTask;
            if (autoDividendTask != null) {
                autoDividendTask.cancel(true);
            }
        }
    });
}

From source file:pt.webdetails.cda.dataaccess.JoinCompoundDataAccess.java

private String getInjectorStepXmlString(String name, TableModel t) {
    StringBuilder xml = new StringBuilder("<step><name>");
    Class<?> columnClass;/*from   w  w w.j av a  2  s. co  m*/
    xml.append(name).append("</name><type>Injector</type><copies>1</copies>");

    int maxRowsTypeSearch = getMaxTypeSearchRowCount(t);

    // If we have metadata information, put it here
    if (t.getColumnCount() > 0) {

        xml.append("<fields>");
        for (int i = 0; i < t.getColumnCount(); i++) {
            /* The proper way to get the column class is from t.getColumnClass().
             * However, this always returns Object when the column at hand is a
             * Calculated Column -- and we have no idea what to do with Objects.
             * Therefore, we try to infer the correct type from the getClass() of
             * the chosen column, first row, as that can't be worse than trying
             * to deal with Object.
             */
            columnClass = t.getColumnClass(i);
            if (columnClass.equals(Object.class) && t.getRowCount() > 0) {
                for (int j = 0; j < maxRowsTypeSearch; j++) {
                    if (t.getValueAt(j, i) != null) {
                        columnClass = t.getValueAt(j, i).getClass();
                        break;
                    }
                }
            }
            xml.append("<field>");
            xml.append("<name>").append(t.getColumnName(i)).append("</name>");
            xml.append("<type>").append(getKettleTypeFromColumnClass(columnClass)).append("</type>");
            xml.append("<length>-1</length><precision>-1</precision></field>");
        }
        xml.append("</fields>");

    }

    xml.append("</step>");
    return xml.toString();

}

From source file:pt.webdetails.cda.exporter.JsonExporter.java

public JSONObject getTableAsJson(TableModel tableModel, Integer rowLimit)
        throws JSONException, ExporterException {
    JSONObject json = new JSONObject();

    // Generate metadata
    final JSONArray metadataArray = new JSONArray();

    final int columnCount = tableModel.getColumnCount();
    int rowCount = tableModel.getRowCount();

    if (rowLimit != null) {
        rowCount = Math.min(rowCount, rowLimit);
    }//from w w w. ja  v  a2 s.c o  m

    boolean[] isColumnDouble = new boolean[columnCount];
    for (int i = 0; i < columnCount; i++) {
        JSONObject info = new JSONObject();
        info.put("colIndex", i);
        info.put("colName", tableModel.getColumnName(i));
        Class<?> columnClass = tableModel.getColumnClass(i);
        isColumnDouble[i] = (columnClass.isAssignableFrom(Double.class));
        info.put("colType", getColType(columnClass));
        metadataArray.put(info);
    }
    json.put("metadata", metadataArray);

    if (tableModel instanceof MetadataTableModel) {
        json.put("queryInfo", ((MetadataTableModel) tableModel).getAllMetadata());
    }
    final JSONArray valuesArray = new JSONArray();

    for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) {
        final JSONArray rowArray = new JSONArray();
        for (int colIdx = 0; colIdx < columnCount; colIdx++) {
            Object value = tableModel.getValueAt(rowIdx, colIdx);
            try {
                if (value != null && isColumnDouble[colIdx] && ((Double) value).isInfinite()) {
                    value = null;
                    //value = Double.POSITIVE_INFINITY == (Double) value ? "Infinity" : "-Infinity";//workaround for JSON
                    // issue with Infinity
                }
            } catch (ClassCastException e) {
            } //just because it says Double doesn't mean we don't get oranges
            rowArray.put(value);
        }
        valuesArray.put(rowArray);
    }
    json.put("resultset", valuesArray);
    return json;
}

From source file:pt.webdetails.cda.exporter.XmlExporter.java

public void export(final OutputStream out, final TableModel tableModel) throws ExporterException {
    final Document document = DocumentHelper.createDocument();

    // Generate metadata
    final Element root = document.addElement("CdaExport");
    final Element metadata = root.addElement("MetaData");

    final int columnCount = tableModel.getColumnCount();
    final int rowCount = tableModel.getRowCount();

    for (int i = 0; i < columnCount; i++) {
        final Element columnInfo = metadata.addElement("ColumnMetaData");
        columnInfo.addAttribute("index", (String.valueOf(i)));
        columnInfo.addAttribute("type", getColType(tableModel.getColumnClass(i)));
        columnInfo.addAttribute("name", tableModel.getColumnName(i));

    }/*from   w  w w  . j av a 2 s  .c  o m*/

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
    final Element resultSet = root.addElement("ResultSet");
    for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) {

        final Element row = resultSet.addElement("Row");

        for (int colIdx = 0; colIdx < columnCount; colIdx++) {
            final Element col = row.addElement("Col");

            final Object value = tableModel.getValueAt(rowIdx, colIdx);
            if (value instanceof Date) {
                col.setText(format.format(value));
            } else if (value != null) {
                // numbers can be safely converted via toString, as they use a well-defined format there
                col.setText(value.toString());
            } else {
                col.addAttribute("isNull", "true");
            }

        }
    }

    try {
        final Writer writer = new BufferedWriter(new OutputStreamWriter(out));

        document.setXMLEncoding("UTF-8");
        document.write(writer);
        writer.flush();
    } catch (IOException e) {
        throw new ExporterException("IO Exception converting to utf-8", e);
    }
}

From source file:pt.webdetails.cda.utils.TableModelUtils.java

public static TableModel postProcessTableModel(final DataAccess dataAccess, final QueryOptions queryOptions,
        final TableModel rawTableModel) throws SortException, InvalidOutputIndexException {

    if (rawTableModel == null) {
        throw new IllegalArgumentException("Cannot process null table.");
    }//from w w  w.  j ava2  s .  c om

    // We will:
    //  1. Evaluate Calculated columns
    //  2. Show only the output columns we want;
    //  3. Sort
    //  4. Pagination

    TableModel table;

    // 1 Evaluate Calculated columns
    table = evaluateCalculatedColumns(dataAccess, rawTableModel);

    //  2. Show only the output columns we want, filter rows
    List<Integer> outputIndexes = getOutputIndexes(dataAccess, queryOptions, table);
    DataTableFilter rowFilter = getRowFilter(queryOptions, outputIndexes);
    //mdx and denormalizedMdx queries with an empty result set can return different metadata (less columns),
    //in this cases, the output indexes will be ignored
    boolean useOutputIndexes = true;
    if (table.getRowCount() == 0
            && (dataAccess.getType().equals("mdx") || dataAccess.getType().equals("denormalizedMdx"))) {
        useOutputIndexes = false;
        logger.warn("Mdx query returned empty result set, output indexes will be ignored.");
    }
    table = useOutputIndexes ? filterTable(table, outputIndexes, rowFilter)
            : filterTable(table, new ArrayList<Integer>(), rowFilter);

    //  3. Sort
    if (!queryOptions.getSortBy().isEmpty()) {
        // no action
        table = (new SortTableModel()).doSort(table, queryOptions.getSortBy());
    }

    // Create a metadata-aware table model

    final Class<?>[] colTypes = new Class[table.getColumnCount()];
    final String[] colNames = new String[table.getColumnCount()];

    for (int i = 0; i < table.getColumnCount(); i++) {
        colTypes[i] = table.getColumnClass(i);
        colNames[i] = table.getColumnName(i);
    }

    final int rowCount = table.getRowCount();
    MetadataTableModel result = new MetadataTableModel(colNames, colTypes, rowCount);
    result.setMetadata("totalRows", rowCount);
    for (int r = 0; r < rowCount; r++) {
        for (int j = 0; j < table.getColumnCount(); j++) {
            result.setValueAt(table.getValueAt(r, j), r, j);
        }
    }
    //  4. Pagination
    return paginateTableModel(result, queryOptions);

}

From source file:pt.webdetails.cda.utils.TableModelUtils.java

/**
 * @param table//from w  w  w. j  ava 2 s.  com
 * @param outputIndexes
 * @param rowFilter     (optional)
 * @return
 * @throws InvalidOutputIndexException
 */
private static TableModel filterTable(final TableModel table, List<Integer> outputIndexes,
        final DataTableFilter rowFilter) throws InvalidOutputIndexException {
    int columnCount = outputIndexes.size();

    if (columnCount == 0 && rowFilter != null) { //still have to go through the motions if we need to filter rows

        for (int i = 0; i < table.getColumnCount(); i++) {
            outputIndexes.add(i);
        }
        columnCount = outputIndexes.size();
    }

    if (columnCount != 0) {
        //logger.info(Collections.max(outputIndexes)+" "+table.getColumnCount());
        if ((Collections.max(outputIndexes) > table.getColumnCount() - 1)) {
            String errorMessage = String.format(
                    "Output index higher than number of columns in tableModel. %s > %s",
                    Collections.max(outputIndexes), table.getColumnCount());
            logger.error(errorMessage);

            if (table.getColumnCount() > 0) {
                throw new InvalidOutputIndexException(errorMessage, null);
            } else {
                logger.warn(
                        "Unable to validate output indexes because table metadata is empty. Returning table.");
                return table;
            }
        }

        final int rowCount = table.getRowCount();
        logger.debug(rowCount == 0 ? "No data found" : "Found " + rowCount + " rows");

        final Class<?>[] colTypes = new Class[columnCount];
        final String[] colNames = new String[columnCount];
        //just set the number of rows/columns
        final TypedTableModel typedTableModel = new TypedTableModel(colNames, colTypes, rowCount);

        for (int rowIn = 0, rowOut = 0; rowIn < rowCount; rowIn++, rowOut++) {
            //filter rows
            if (rowFilter != null && !rowFilter.rowContainsSearchTerms(table, rowIn)) {
                rowOut--;
                continue;
            }
            //filter columns
            for (int j = 0; j < outputIndexes.size(); j++) {
                final int outputIndex = outputIndexes.get(j);
                typedTableModel.setValueAt(table.getValueAt(rowIn, outputIndex), rowOut, j);
            }
        }

        //since we set the calculated table model to infer types, they will be available after rows are evaluated
        for (int i = 0; i < outputIndexes.size(); i++) {
            final int outputIndex = outputIndexes.get(i);
            typedTableModel.setColumnName(i, table.getColumnName(outputIndex));
            typedTableModel.setColumnType(i, table.getColumnClass(outputIndex));
        }
        return typedTableModel;
    }
    return table;
}

From source file:pt.webdetails.cda.utils.TableModelUtils.java

public static TableModel copyTableModel(final DataAccess dataAccess, final TableModel t) {

    // We're removing the ::table-by-index:: cols

    // Build an array of column indexes whose name is different from ::table-by-index::.*
    ArrayList<String> namedColumns = new ArrayList<String>();
    ArrayList<Class<?>> namedColumnsClasses = new ArrayList<Class<?>>();
    for (int i = 0; i < t.getColumnCount(); i++) {
        String colName = t.getColumnName(i);
        if (!colName.startsWith("::table-by-index::") && !colName.startsWith("::column::")) {
            namedColumns.add(colName);//from  w w w  .  ja va 2s  .c  o m
            namedColumnsClasses.add(t.getColumnClass(i));
        }
    }

    final int count = namedColumns.size();

    final Class<?>[] colTypes = namedColumnsClasses.toArray(new Class[] {});
    final String[] colNames = namedColumns.toArray(new String[] {});

    for (int i = 0; i < count; i++) {
        colTypes[i] = t.getColumnClass(i);

        final ColumnDefinition col = dataAccess.getColumnDefinition(i);
        colNames[i] = col != null ? col.getName() : t.getColumnName(i);
    }
    final int rowCount = t.getRowCount();
    logger.debug(rowCount == 0 ? "No data found" : "Found " + rowCount + " rows");
    //if the first row has no values, the class will be Object, however, next rows can have values, we evaluate those
    for (int i = 0; i < colTypes.length; i++) {
        if (colTypes[i] == Object.class) {
            for (int k = 0; k < t.getRowCount(); k++) {
                if (t.getValueAt(k, i) != null) {
                    colTypes[i] = t.getValueAt(k, i).getClass();
                    break;
                }
            }
        }
    }

    final TypedTableModel typedTableModel = new TypedTableModel(colNames, colTypes, rowCount);
    for (int r = 0; r < rowCount; r++) {
        for (int c = 0; c < count; c++) {
            typedTableModel.setValueAt(t.getValueAt(r, c), r, c);
        }
    }
    return typedTableModel;
}

From source file:pt.webdetails.cda.utils.TableModelUtils.java

/**
 * Method to append a tablemodel into another. We'll make no guarantees about the types
 *
 * @param tableModelA TableModel to be modified
 * @param tableModelB Contents to be appended #
 *///w  w w  . j ava 2s  .  c  o  m
public static TableModel appendTableModel(final TableModel tableModelA, final TableModel tableModelB) {

    // We will believe the data is correct - no type checking

    int colCountA = tableModelA.getColumnCount(), colCountB = tableModelB.getColumnCount();
    boolean usingA = colCountA > colCountB;
    int colCount = usingA ? colCountA : colCountB;
    TableModel referenceTable = (usingA ? tableModelA : tableModelB);

    final Class<?>[] colTypes = new Class[colCount];
    final String[] colNames = new String[colCount];

    for (int i = 0; i < referenceTable.getColumnCount(); i++) {
        colTypes[i] = referenceTable.getColumnClass(i);
        colNames[i] = referenceTable.getColumnName(i);
    }

    int rowCount = tableModelA.getRowCount() + tableModelB.getRowCount();

    // Table A
    final TypedTableModel typedTableModel = new TypedTableModel(colNames, colTypes, rowCount);
    for (int r = 0; r < tableModelA.getRowCount(); r++) {
        for (int c = 0; c < colTypes.length; c++) {
            typedTableModel.setValueAt(tableModelA.getValueAt(r, c), r, c);
        }
    }

    // Table B
    int rowCountOffset = tableModelA.getRowCount();
    for (int r = 0; r < tableModelB.getRowCount(); r++) {
        for (int c = 0; c < colTypes.length; c++) {
            typedTableModel.setValueAt(tableModelB.getValueAt(r, c), r + rowCountOffset, c);
        }
    }

    return typedTableModel;

}