Example usage for javax.swing.table TableModel getColumnName

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

Introduction

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

Prototype

public String getColumnName(int columnIndex);

Source Link

Document

Returns the name of the column at columnIndex.

Usage

From source file:org.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java

private static DataRow createReportParameterDataRow(final TableModel burstingData, final int row) {
    final int columnCount = burstingData.getColumnCount();
    final String[] columnNames = new String[columnCount];
    final Object[] columnValues = new Object[columnCount];
    for (int i = 0; i < columnCount; i++) {
        columnValues[i] = burstingData.getValueAt(row, i);
        columnNames[i] = burstingData.getColumnName(i);
    }/*w  ww  .  j ava  2s. c o  m*/
    return new StaticDataRow(columnNames, columnValues);
}

From source file:org.rivalry.swingui.table.VisibleColumnsPopupMenu.java

/**
 * @param columnName Column name.//from   w w w.  ja  v a  2  s .  co  m
 * 
 * @return the absolute column index.
 */
int determineColumnIndex(final String columnName) {
    int answer = -1;

    if (StringUtils.isNotEmpty(columnName)) {
        final TableModel dataModel = _tableModel.getDataModel();
        final int size = dataModel.getColumnCount();

        for (int i = 0; answer < 0 && i < size; i++) {
            if (columnName.equals(dataModel.getColumnName(i))) {
                answer = i;
            }
        }
    }

    return answer;
}

From source file:org.wings.STable.java

/**
 * Creates the default columns of the table from the table model.
 */// www . j av  a 2s. c o m
public void createDefaultColumnsFromModel() {
    TableModel tm = getModel();

    if (tm != null) {
        STableColumnModel columnModel = getColumnModel();
        while (columnModel.getColumnCount() > 0)
            columnModel.removeColumn(columnModel.getColumn(0));

        for (int i = 0; i < tm.getColumnCount(); i++) {
            STableColumn column = new STableColumn(i);
            String columnName = tm.getColumnName(i);
            column.setHeaderValue(columnName);
            this.columnModel.addColumn(column);
        }
    }
}

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

/**
 * Construct Statements based on given TableModel.
 *
 * @param tableModel given TableModel/*from w w w  .j a  v  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 int getModelColumnIndex(JTable jTable, Object value) {

    TableModel tableModel = jTable.getModel();

    if (tableModel instanceof StockTableModel) {

        return ((StockTableModel) tableModel).findColumn(value.toString());

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

    try {

        TableColumn tableColumn = jTable.getColumn(value);

        return tableColumn.getModelIndex();

    } // Anti-pattern. We are depending on the exception throwing. Bad!

    catch (java.lang.IllegalArgumentException exp) {

        final int columnCount = tableModel.getColumnCount();

        for (int col = 0; col < columnCount; col++) {

            String s = tableModel.getColumnName(col);

            if (s.equals(value))

                return col;

        }

    }

    return -1;

}

From source file:pt.webdetails.cda.CdaQueryComponent.java

private IPentahoResultSet convertTableToResultSet(TableModel tableModel) {
    List<String> columnNames = new ArrayList<String>();
    for (int i = 0; i < tableModel.getColumnCount(); i++) {
        columnNames.add(tableModel.getColumnName(i));
    }//  www. j  a va2s .c  o m
    MemoryMetaData metadata = new MemoryMetaData(columnNames);

    MemoryResultSet resultSet = new MemoryResultSet();
    resultSet.setMetaData(metadata);
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        Object row[] = new Object[tableModel.getColumnCount()];
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            row[j] = tableModel.getValueAt(i, j);
        }
        resultSet.addRow(row);
    }
    return resultSet;
}

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

protected TableModel queryDataSource(final QueryOptions queryOptions) throws QueryException {
    TableModel output;/*from ww w  . j av a 2s .  co  m*/
    inputCallables.clear();

    try {
        QueryOptions croppedOptions = (QueryOptions) queryOptions.clone();
        croppedOptions.setSortBy(new ArrayList<String>());
        croppedOptions.setPageSize(0);
        croppedOptions.setPageStart(0);
        final TableModel tableModelA = this.getCdaSettings().getDataAccess(leftId).doQuery(croppedOptions);
        final TableModel tableModelB = this.getCdaSettings().getDataAccess(rightId).doQuery(croppedOptions);

        if (tableModelA.getColumnCount() == 0 || tableModelB.getColumnCount() == 0) {
            return new MetadataTableModel(new String[0], new Class[0], 0);

        }

        String[] leftColumnNames = new String[leftKeys.length];
        for (int i = 0; i < leftKeys.length; i++) {
            leftColumnNames[i] = tableModelA.getColumnName(Integer.parseInt(leftKeys[i]));
        }

        String[] rightColumnNames = new String[rightKeys.length];
        for (int i = 0; i < rightKeys.length; i++) {
            rightColumnNames[i] = tableModelB.getColumnName(Integer.parseInt(rightKeys[i]));
        }

        String sortLeftXML = getSortXmlStep("sortLeft", leftColumnNames);
        String sortRightXML = getSortXmlStep("sortRight", rightColumnNames);

        String mergeJoinXML = getMergeJoinXml(leftColumnNames, rightColumnNames);

        DynamicTransMetaConfig transMetaConfig = new DynamicTransMetaConfig(Type.EMPTY, "JoinCompoundData",
                null, null);
        DynamicTransConfig transConfig = new DynamicTransConfig();

        String input1Xml = getInjectorStepXmlString("input1", tableModelA);
        String input2Xml = getInjectorStepXmlString("input2", tableModelB);

        transConfig.addConfigEntry(EntryType.STEP, "input1", input1Xml);
        transConfig.addConfigEntry(EntryType.STEP, "input2", input2Xml);
        transConfig.addConfigEntry(EntryType.STEP, "sortLeft", sortLeftXML);
        transConfig.addConfigEntry(EntryType.STEP, "sortRight", sortRightXML);
        transConfig.addConfigEntry(EntryType.STEP, "mergeJoin", mergeJoinXML);

        transConfig.addConfigEntry(EntryType.HOP, "input1", "sortLeft");
        transConfig.addConfigEntry(EntryType.HOP, "input2", "sortRight");
        transConfig.addConfigEntry(EntryType.HOP, "sortLeft", "mergeJoin");
        transConfig.addConfigEntry(EntryType.HOP, "sortRight", "mergeJoin");

        TableModelInput input1 = new TableModelInput();
        transConfig.addInput("input1", input1);
        inputCallables.add(input1.getCallableRowProducer(tableModelA, true));
        TableModelInput input2 = new TableModelInput();
        transConfig.addInput("input2", input2);
        inputCallables.add(input2.getCallableRowProducer(tableModelB, true));

        RowMetaToTableModel outputListener = new RowMetaToTableModel(false, true, false);
        transConfig.addOutput("mergeJoin", outputListener);

        DynamicTransformation trans = new DynamicTransformation(transConfig, transMetaConfig);
        trans.executeCheckedSuccess(null, null, this);
        logger.info(trans.getReadWriteThroughput());
        output = outputListener.getRowsWritten();

        if (output == null) {
            return new MetadataTableModel(new String[0], new Class[0], 0);
        }
    } catch (UnknownDataAccessException e) {
        throw new QueryException("Unknown Data access in CompoundDataAccess ", e);
    } catch (Exception e) {
        throw new QueryException("Exception during query ", e);
    }
    return output;
}

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 a va2  s  .com
    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.HtmlExporter.java

@Override
public void export(OutputStream out, TableModel tableModel) throws ExporterException {
    final Document document = DocumentHelper.createDocument();
    Element table = null;/*  w w w .ja v a2s.c  o  m*/

    if (fullHtml) {
        final Element html = document.addElement("html");
        final Element head = html.addElement("head");
        head.addElement("title").addText(title);
        table = html.addElement("body").addElement("table");
    } else {
        table = document.addElement("table");
    }

    final int columnCount = tableModel.getColumnCount();

    //table headers
    final Element headerRow = table.addElement("tr");
    for (int i = 0; i < columnCount; i++) {
        String colName = tableModel.getColumnName(i);
        headerRow.addElement("th").addText(colName);
    }

    //table body
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        Element row = table.addElement("tr");

        for (int j = 0; j < columnCount; j++) {
            Element tableCell = row.addElement("td");
            Object value = tableModel.getValueAt(i, j);
            tableCell.setText(valueToText(value));

            if (value instanceof Date) {
                tableCell.setText(format.format(value));
            } else if (value != null) {
                // numbers can be safely converted via toString, as they use a well-defined format there
                tableCell.setText(value.toString());
            }

        }
    }

    try {
        document.setXMLEncoding("UTF-8");

        OutputFormat outFormat = new OutputFormat();
        outFormat.setOmitEncoding(true);
        outFormat.setSuppressDeclaration(true);//otherwise msexcel/oocalc may not recognize content
        outFormat.setNewlines(true);
        outFormat.setIndentSize(columnCount);
        final Writer writer = new BufferedWriter(new OutputStreamWriter(out));
        XMLWriter xmlWriter = new XMLWriter(writer, outFormat);
        xmlWriter.write(document);
        xmlWriter.flush();
    } catch (IOException e) {
        throw new ExporterException("IO Exception converting to utf-8", e);
    }
}

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 .j a  va 2 s  .  c om*/

    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;
}