Example usage for javax.swing.table TableModel getColumnCount

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

Introduction

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

Prototype

public int getColumnCount();

Source Link

Document

Returns the number of columns in the model.

Usage

From source file:au.com.jwatmuff.eventmanager.export.CSVExporter.java

public static void generateFromTable(TableModel tm, OutputStream out) {
    int rows = tm.getRowCount();
    int cols = tm.getColumnCount();
    Object[][] table = new Object[rows + 1][cols];
    for (int j = 0; j < cols; j++)
        table[0][j] = tm.getColumnName(j);
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            table[i + 1][j] = tm.getValueAt(i, j);

    generateFromArray(table, out);/*from   www.j  a v a2s . c o  m*/
}

From source file:Main.java

/**
 * Auto fit the column of a table./*w  w  w .  j a  v  a  2 s . co  m*/
 * @param table the table for which to auto fit the columns.
 * @param columnIndex the index of the column to auto fit.
 * @param maxWidth the maximum width that a column can take (like Integer.MAX_WIDTH).
 */
public static void autoFitTableColumn(JTable table, int columnIndex, int maxWidth) {
    TableModel model = table.getModel();
    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
    int rowCount = table.getRowCount();
    for (int i = columnIndex >= 0 ? columnIndex : model.getColumnCount() - 1; i >= 0; i--) {
        TableColumn column = table.getColumnModel().getColumn(i);
        int headerWidth = headerRenderer
                .getTableCellRendererComponent(table, column.getHeaderValue(), false, false, 0, 0)
                .getPreferredSize().width;
        int cellWidth = 0;
        for (int j = 0; j < rowCount; j++) {
            Component comp = table.getDefaultRenderer(model.getColumnClass(i))
                    .getTableCellRendererComponent(table, table.getValueAt(j, i), false, false, 0, i);
            int preferredWidth = comp.getPreferredSize().width;
            // Artificial space to look nicer.
            preferredWidth += 10;
            cellWidth = Math.max(cellWidth, preferredWidth);
        }
        // Artificial space for the sort icon.
        headerWidth += 20;
        column.setPreferredWidth(Math.min(Math.max(headerWidth, cellWidth) + table.getRowMargin(), maxWidth));
        if (columnIndex >= 0) {
            break;
        }
    }
}

From source file:Main.java

/**
 * Save the contents of a table to a TSV file
 * Note:  uses toString() on the header cells as well as the data cells.  If you've got funny columns,
 * expect funny behavior//from  w  ww.  j  ava 2  s .c o m
 * @param table
 * @param outFile
 * @throws IOException
 */
public static void SaveTableAsTSV(JTable table, File outFile) throws IOException {
    PrintWriter outPW = new PrintWriter(outFile);

    TableModel tableModel = table.getModel();
    TableColumnModel columnModel = table.getColumnModel();

    StringBuffer headerLineBuf = new StringBuffer();
    for (int i = 0; i < columnModel.getColumnCount(); i++) {
        if (i > 0)
            headerLineBuf.append("\t");
        headerLineBuf.append(columnModel.getColumn(i).getHeaderValue().toString());
    }
    outPW.println(headerLineBuf.toString());
    outPW.flush();
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        StringBuffer lineBuf = new StringBuffer();
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            if (j > 0)
                lineBuf.append("\t");
            lineBuf.append(tableModel.getValueAt(i, j).toString());
        }
        outPW.println(lineBuf.toString());
        outPW.flush();
    }
    outPW.close();
}

From source file:com.limegroup.gnutella.gui.GUIUtils.java

/**
 * It will adjust the column width to match the widest element.
 * (You might not want to use this for every column, consider some columns might be really long)
 * @param model/*from w ww.j a  v  a2s .c  o  m*/
 * @param columnIndex
 * @param table
 * @return
 */
public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding,
        JTable table) {

    if (columnIndex > model.getColumnCount() - 1) {
        //invalid column index
        return;
    }

    if (!model.getColumnClass(columnIndex).equals(String.class)) {
        return;
    }

    String longestValue = "";
    for (int row = 0; row < model.getRowCount(); row++) {
        String strValue = (String) model.getValueAt(row, columnIndex);
        if (strValue != null && strValue.length() > longestValue.length()) {
            longestValue = strValue;
        }
    }

    Graphics g = table.getGraphics();

    try {
        int suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g)
                .getWidth();
        table.getColumnModel().getColumn(columnIndex)
                .setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth) + rightPadding);
    } catch (Exception e) {
        table.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth);
        e.printStackTrace();
    }

}

From source file:edu.scripps.fl.pubchem.xml.extract.XMLExtractor.java

public Map<Integer, String> getColumnsMap(TableModel tableModel) {
    Map<Integer, String> map = new CaseInsensitiveMap();
    for (int ii = 0; ii < tableModel.getColumnCount(); ii++) {
        String name = tableModel.getColumnName(ii);
        if (null != name) { // excel sometimes adds null columns
            name = name.replaceAll("[-\\s+]", "");
            map.put(ii, name);/*from www . java  2  s.co m*/
        }
    }
    return map;
}

From source file:fll.web.FullTournamentTest.java

/**
 * Find a column index in a table model by name.
 * //  ww w  .  j a va 2  s  . c  om
 * @return -1 if not found
 */
private static int findColumnByName(final TableModel tableModel, final String name) {
    for (int i = 0; i < tableModel.getColumnCount(); ++i) {
        if (name.equals(tableModel.getColumnName(i))) {
            return i;
        }
    }
    return -1;
}

From source file:edu.scripps.fl.pubchem.xml.PopulateArray.java

public Map<String, Integer> getColumnsMap(TableModel tableModel) {

    Map<String, Integer> map = new CaseInsensitiveMap();
    for (int ii = 0; ii < tableModel.getColumnCount(); ii++) {
        String name = tableModel.getColumnName(ii);
        if (null != name) { // excel sometimes adds null columns
            name = name.replaceAll("[-\\s+]", "");
            map.put(name, ii);//  w  ww .  j av  a 2s. c om
        }
    }
    return map;
}

From source file:at.tuwien.ifs.feature.evaluation.SimilarityRetrievalGUI.java

private void initButtonSaveResults() {
    btnSaveResults = new JButton("Save as ...");
    btnSaveResults.setEnabled(false); // can't save right away, need a first search
    btnSaveResults.addActionListener(new ActionListener() {
        @Override//from  ww  w .j  a v  a 2  s .c om
        public void actionPerformed(ActionEvent e) {
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            if (fileChooser.getSelectedFile() != null) { // reusing the dialog
                fileChooser.setSelectedFile(null);
            }

            int returnVal = fileChooser.showDialog(SimilarityRetrievalGUI.this, "Save results to file ...");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    PrintWriter w = FileUtils.openFileForWriting("Results file",
                            fileChooser.getSelectedFile().getAbsolutePath());
                    TableModel model = resultsTable.getModel();

                    // column headers
                    for (int col = 0; col < model.getColumnCount(); col++) {
                        w.print(model.getColumnName(col) + "\t");
                    }
                    w.println();

                    // write each data row
                    for (int row = 0; row < model.getRowCount(); row++) {
                        for (int col = 0; col < model.getColumnCount(); col++) {
                            w.print(model.getValueAt(row, col) + "\t");
                        }
                        w.println();
                    }
                    w.flush();
                    w.close();
                    JOptionPane.showMessageDialog(SimilarityRetrievalGUI.this,
                            "Successfully wrote to file " + fileChooser.getSelectedFile().getAbsolutePath(),
                            "Results stored", JOptionPane.INFORMATION_MESSAGE);

                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    });
}

From source file:uk.ac.lkl.cram.ui.report.Report.java

private void addSummary() {
    MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
    mdp.addStyledParagraphOfText("Heading1", "Summary");
    Tbl table = factory.createTbl();/*  w  w  w  . j  a  va2 s .  co  m*/
    Tr tableHead = factory.createTr();
    TableModel tableModel = new SummaryReportModel(module);
    int columnCount = tableModel.getColumnCount();
    for (int col = 0; col < columnCount; col++) {
        addTableCell(tableHead, tableModel.getColumnName(col), JcEnumeration.CENTER, true);
    }
    table.getContent().add(tableHead);
    for (int row = 0; row < tableModel.getRowCount(); row++) {
        boolean lastRow = row == tableModel.getRowCount() - 1;
        Tr tableRow = factory.createTr();
        if (lastRow) {
            addTableCell(tableRow, tableModel.getValueAt(row, 0).toString(), JcEnumeration.LEFT, true);
        } else {
            addSimpleTableCell(tableRow, tableModel.getValueAt(row, 0).toString());
        }
        for (int col = 1; col < columnCount; col++) {
            if (row > 4) {
                addTableCell(tableRow, CURRENCY_FORMATTER.format(tableModel.getValueAt(row, col)),
                        JcEnumeration.RIGHT, lastRow);
            } else {
                addTableCell(tableRow, INTEGER_FORMATTER.format(tableModel.getValueAt(row, col)),
                        JcEnumeration.RIGHT, lastRow);
            }
        }
        table.getContent().add(tableRow);
    }
    addBorders(table);
    mdp.addObject(table);
}

From source file:uk.ac.lkl.cram.ui.report.Report.java

private void addLearningActivities() {
    MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
    mdp.addStyledParagraphOfText("Heading1", "Learning Activities");
    float online_hours = 0f;
    float f2f_hours = 0f;
    Tbl table = factory.createTbl();//from   w w  w.j  a  va 2s.  c  o m
    Tr tableHead = factory.createTr();
    TableModel tableModel = new ModuleReportModel(module);
    for (int col = 0; col < tableModel.getColumnCount(); col++) {
        addTableCell(tableHead, tableModel.getColumnName(col), JcEnumeration.CENTER, true);
    }
    table.getContent().add(tableHead);
    int columnCount = tableModel.getColumnCount();
    for (int row = 0; row < tableModel.getRowCount(); row++) {
        boolean lastRow = row == tableModel.getRowCount() - 1;
        Tr tableRow = factory.createTr();
        addTableCell(tableRow, tableModel.getValueAt(row, 0).toString(), JcEnumeration.LEFT, lastRow);
        for (int col = 1; col < columnCount; col++) {
            addTableCell(tableRow, FLOAT_FORMATTER.format(tableModel.getValueAt(row, col)), JcEnumeration.RIGHT,
                    lastRow);
        }
        table.getContent().add(tableRow);
    }
    addBorders(table);
    List<TLALineItem> lineItems = module.getTLALineItems();
    for (TLALineItem lineItem : lineItems) {
        TLActivity activity = lineItem.getActivity();
        float totalLearnerHourCount = lineItem.getTotalLearnerHourCount(module);
        StudentTeacherInteraction sti = activity.getStudentTeacherInteraction();
        if (sti.isOnline()) {
            online_hours += totalLearnerHourCount;
        }
        if (sti.isTutorSupported() && sti.isLocationSpecific()) {
            f2f_hours += totalLearnerHourCount;
        }
    }
    mdp.addStyledParagraphOfText("BodyText", "Number of learner hours online: " + (int) online_hours);
    mdp.addStyledParagraphOfText("BodyText", "Number of learner hours face-to-face: " + (int) f2f_hours);
    addBorders(table);
    mdp.addObject(table);
}