/** * Static function for exporting a JXTable to a CSV text file * * @param table - table to export * @param file - file to export to */ public static void exportToCSV(JXTable table, File file) { int i = 0; int j = 0; try { TableModel model = table.getModel(); FileWriter csv = new FileWriter(file); for (i = 0; i < model.getColumnCount(); i++) { csv.write(model.getColumnName(i) + ","); } csv.write(System.getProperty("line.separator")); for (i = 0; i < model.getRowCount(); i++) { for (j = 0; j < (model.getColumnCount()); j++) { if (model.getValueAt(i, j) == null) { csv.write("" + ","); } else { csv.write(model.getValueAt(i, j).toString() + ","); } } csv.write(System.getProperty("line.separator")); } csv.close(); } catch (IOException e) { JOptionPane.showMessageDialog( App.mainFrame, "Error saving file '" + file.getName() + "'\n" + e.getLocalizedMessage()); e.printStackTrace(); } }
private int[] getWidths(TableModel tableModel) { int[] widths = new int[tableModel.getColumnCount()]; for (int r = 0; r < Math.min(tableModel.getRowCount(), 500); r++) { // 500 is not for performance, but for using only a sample of data with huge table for (int c = 0; c < tableModel.getColumnCount(); c++) { Object o = tableModel.getValueAt(r, c); if (o instanceof String) { String s = ((String) o).trim(); if (s.length() > widths[c]) widths[c] = s.length(); } } } return widths; }
private void clearModel() { for (int row = 0; row < lifeModel.getRowCount(); row++) { for (int col = 0; col < lifeModel.getColumnCount(); col++) { lifeModel.setValueAt(new LifeCell(), row, col); } } }
/** * Constructs a ClutoTree diaplay which is initialized with tableModel as the data model, and the * given selection model. * * @param clutoSolution The clustering solution * @param tableContext The context which manages views and selections. * @param tableModel the data model for the parallel coordinate display */ public ClutoTree(ClutoSolution clutoSolution, TableContext tableContext, TableModel tableModel) { ctx = tableContext; tm = tableModel; lsm = ctx.getRowSelectionModel(tm); // labelModel int ncol = tm.getColumnCount(); for (int i = 0; i < ncol; i++) { labelModel.addElement(tm.getColumnName(i)); } setLayout(new BorderLayout()); btnP = new JToolBar(); add(btnP, BorderLayout.NORTH); labelChoice.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { labelColumn = 0; String ln = (String) e.getItem(); if (ln != null) { for (int c = 0; c < tm.getColumnCount(); c++) { if (ln.equals(tm.getColumnName(c))) { labelColumn = c; break; } } } graph.invalidate(); validate(); repaint(); } } }); btnP.add(labelChoice); graph = new SimpleGraph(); graph.getGraphDisplay().setOpaque(true); graph.getGraphDisplay().setBackground(Color.white); graph.getGraphDisplay().setGridColor(new Color(220, 220, 220)); graph.showGrid(false); graph.showAxis(BorderLayout.WEST, false); graph.showAxis(BorderLayout.EAST, true); graph.getAxisDisplay(BorderLayout.EAST).setZoomable(true); graph.getAxisDisplay(BorderLayout.EAST).setAxisLabeler(labeler); ((LinearAxis) graph.getYAxis()).setTickIncrement(-1.); graph.getAxisDisplay(BorderLayout.SOUTH).setZoomable(true); gs = new GraphSegments(); gs.setColor(Color.blue); idxSelColor = new IndexSelectColor(Color.cyan, null, new DefaultListSelectionModel()); gs.setIndexedColor(idxSelColor); graph.addGraphItem(gs); graph.getGraphDisplay().addMouseListener(ma); add(graph); if (lsm != null) { lsm.addListSelectionListener(selListener); } display(makeTree(clutoSolution)); }
private Object performQuery( final ReportFormulaContext context, final String query, final String columnName, final int queryTimeout, final int queryLimit) { try { final DataFactory dataFactory = context.getRuntime().getDataFactory(); final TableModel tableModel = dataFactory.queryData( query, new QueryDataRowWrapper(context.getDataRow(), queryLimit, queryTimeout)); if (tableModel == null) { return null; } final int columnCount = tableModel.getColumnCount(); if (tableModel.getRowCount() == 0 || columnCount == 0) { return null; } for (int column = 0; column < columnCount; column++) { if (columnName == null || columnName.equals(tableModel.getColumnName(column))) { final ArrayList<Object> values = new ArrayList<Object>(); final int rowCount = tableModel.getRowCount(); for (int row = 0; row < rowCount; row++) { values.add(tableModel.getValueAt(row, column)); } return values.toArray(); } } } catch (Exception e) { logger.warn("SingleValueQueryFunction: Failed to perform query", e); } return null; }
@Override public void setModel(final TableModel model) { super.setModel(model); if (model instanceof SortableColumnModel) { final SortableColumnModel sortableModel = (SortableColumnModel) model; if (sortableModel.isSortable()) { final TableRowSorter<TableModel> rowSorter = createRowSorter(model); rowSorter.setSortsOnUpdates(isSortOnUpdates()); setRowSorter(rowSorter); final RowSorter.SortKey sortKey = sortableModel.getDefaultSortKey(); if (sortKey != null && sortKey.getColumn() >= 0 && sortKey.getColumn() < model.getColumnCount()) { if (sortableModel.getColumnInfos()[sortKey.getColumn()].isSortable()) { rowSorter.setSortKeys(Arrays.asList(sortKey)); } } } else { final RowSorter<? extends TableModel> rowSorter = getRowSorter(); if (rowSorter instanceof DefaultColumnInfoBasedRowSorter) { setRowSorter(null); } } } }
private void writerHeader(PrintWriter writer, TableModel model) { for (int i = 0; i < model.getColumnCount(); i++) { if (i > 0) writer.print(','); writer.print(model.getColumnName(i)); } writer.println(); }
/** 导出JTable到Excel */ public void exportTable(JTable table, File file) throws IOException { try { OutputStream out = new FileOutputStream(file); TableModel model = table.getModel(); WritableWorkbook wwb = Workbook.createWorkbook(out); WritableSheet ws = wwb.createSheet("关联规则", 0); for (int i = 0; i < model.getColumnCount() - 1; i++) { jxl.write.Label labelN = new jxl.write.Label(i, 0, model.getColumnName(i + 1)); try { ws.addCell(labelN); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException we) { we.printStackTrace(); } } int row = 1; for (int j = 1; j <= model.getRowCount(); ++j) { if (model.getValueAt(j - 1, 0).equals(true)) { for (int i = 0; i < model.getColumnCount() - 1; ++i) { jxl.write.Label labelN = new jxl.write.Label(i, row, model.getValueAt(j - 1, i + 1).toString()); try { ws.addCell(labelN); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException we) { we.printStackTrace(); } } row++; } } wwb.write(); try { wwb.close(); out.close(); } catch (WriteException e) { e.printStackTrace(); } } catch (Exception e) { } }
private void confColumnModel() { for (int row = 0; row < lifeModel.getRowCount(); row++) { for (int col = 0; col < lifeModel.getColumnCount(); col++) { lifeTable.getColumnModel().getColumn(col).setMaxWidth(CELL_SIZE); lifeTable.getColumnModel().getColumn(col).setMinWidth(CELL_SIZE); lifeTable.getColumnModel().getColumn(col).setPreferredWidth(CELL_SIZE); lifeTable.getColumnModel().getColumn(col).setResizable(false); } } }
/** * Validates that queries with empty results (no rows or no columns) are correctly handled by * CachingDataFactory. * * <p>http://jira.pentaho.com/browse/PRD-4628 */ public void testEmptyResult() throws ReportDataFactoryException { final String query = "SELECT NON EMPTY [Product].[All Products].[Classic Cars]" + ".[Highway 66 Mini Classics].[1985 Toyota Supra] " + "on 0 from SteelWheelsSales where measures.Sales\n"; DataFactory dataFactory = createDataFactory(query); final TableModel tableModel = ((CachingDataFactory) dataFactory).queryStatic("default", new ParameterDataRow()); assertEquals("results should be empty, rowcount should be 0.", 0, tableModel.getRowCount()); assertEquals( "results should be empty, columncount should be 0", 0, tableModel.getColumnCount()); }
private int writeData(PrintWriter writer, TableModel model) { int c = 0; for (; c < model.getRowCount(); c++) { for (int i = 0; i < model.getColumnCount(); i++) { if (i > 0) writer.print(','); writer.print(model.getValueAt(c, i)); } writer.println(); } return c; }
private List read() throws Exception { List result = new ArrayList(); TableModel table = executeQuery(); if (table == null) return result; for (int i = 0; i < table.getRowCount(); i++) { KeyAndDescription el = new KeyAndDescription(); int iKey = 0; if (isMultipleKey()) { Iterator itKeyNames = getKeyPropertiesCollection().iterator(); Map key = new HashMap(); boolean isNull = true; while (itKeyNames.hasNext()) { String name = (String) itKeyNames.next(); Object value = table.getValueAt(i, iKey++); key.put(name, value); if (value != null) isNull = false; } if (isNull) { el.setKey(null); } else { el.setKey(getMetaModel().toString(key)); } } else { el.setKey(table.getValueAt(i, iKey++)); } StringBuffer value = new StringBuffer(); int columnCount = table.getColumnCount() - hiddenPropertiesCount; for (int j = iKey; j < columnCount; j++) { value.append(table.getValueAt(i, j)); if (j < table.getColumnCount() - 1) value.append(' '); } el.setDescription(value.toString()); el.setShowCode(true); if (el.getKey() != null) result.add(el); } return result; }
@Override public void tableChanged(TableModelEvent e) { // detect event type if (e.getType() == TableModelEvent.UPDATE) { // new columns has been added TableModel model = (TableModel) e.getSource(); int newColumnCounts = model.getColumnCount(); if (newColumnCounts > columnCounts) { for (int i = columnCounts; i < newColumnCounts; i++) { // create a new column based on the last column TableColumn column = table instanceof JXTable ? new TableColumnExt(i) : new TableColumn(i); column.setHeaderValue(model.getColumnName(i)); // add the new column TableColumnModel columnModel = table.getColumnModel(); columnModel.addColumn(column); } // set the new column counts columnCounts = newColumnCounts; } else { // reset column names int count = model.getColumnCount(); for (int i = 0; i < count; i++) { int viewColumn = table.convertColumnIndexToView(i); if (viewColumn >= 0) { TableColumn column = table.getColumnModel().getColumn(viewColumn); column.setHeaderValue(model.getColumnName(i)); } } table.getTableHeader().repaint(); } } }
/** * Добавить данные из другой таблицы * * @param data - произаольная модель(TableModel) * @return - истина,если данные добавились * @see "добавляет только,если совпадают имена столбцов!" */ public boolean AddData(TableModel data) { if (data.getRowCount() < 1) { return false; } // итак,есть 2 табле модел,надо их объединить: // 1.ищем совпадающие колонки Map<Integer, String> columnNum = new HashMap<Integer, String>(); // List<String> columnName=new ArrayList(); String name1 = "", name2 = ""; for (int i = 0; i < this.getColumnCount(); i++) { name1 = this.getColumnName(i); for (int j = 0; j < data.getColumnCount(); j++) { name2 = data.getColumnName(j); if (name1.equals(name2)) { // columnName.add(name1); columnNum.put(j, name2); // запоминаем индекс и имя столбца break; } } } if (columnNum.isEmpty() == true) { return false; } // 2.добавляем данные // Iterator Iter=columnName.iterator(); Vector newRow = null; Object tmpObj = null; for (int iRow = 0; iRow < data.getRowCount(); iRow++) { // проходим по строкам newRow = this.CreateEmptyRow(); for (Map.Entry<Integer, String> entry : columnNum.entrySet()) { // перебираем все совпавшие колонки tmpObj = data.getValueAt(iRow, entry.getKey()); // получаем значение newRow.setElementAt(tmpObj, entry.getKey()); // заполняем } this.jtData.rows.addElement(newRow); // добавляем новую,заполненную строку int numID = this.GetMaxID() + 1; // текущий максимум int prmColumn = this.GetColumnIndex(this.dbTable.getPrmKey()); this.setValueAt(numID + 1, this.getRowCount(), prmColumn); } this.blockWorkWithDB = true; // теперь обновлять и т.п. нельзя,т.к. потеряем результат объединения return true; }
private JPopupMenu getMyTableColumnSelectionPopupMenu( final JTable jTable1, final int mouseXLocation) { JPopupMenu popup = new JPopupMenu(); TableModel tableModel = jTable1.getModel(); final int col = tableModel.getColumnCount(); for (int i = this.menuStartIndex; i < col; i++) { String name = tableModel.getColumnName(i); // Do not display the menu with name which is ignored by user. if (columnNamesToBeIgnored.contains(name)) { continue; } boolean isVisible = true; try { TableColumn tableColumn = jTable1.getColumn(name); } catch (java.lang.IllegalArgumentException exp) { isVisible = false; } javax.swing.JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(name, isVisible); menuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String name = evt.getActionCommand(); JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) evt.getSource(); if (menuItem.isSelected() == false) { JTableUtilities.removeTableColumn(jTable1, name); } else { TableColumnModel colModel = jTable1.getColumnModel(); int vColIndex = colModel.getColumnIndexAtX(mouseXLocation); JTableUtilities.insertTableColumnFromModel(jTable1, name, vColIndex); } } }); popup.add(menuItem); } return popup; }
/* * (non-Javadoc) * * @see javax.swing.JTable#createDefaultColumnsFromModel() */ public void createDefaultColumnsFromModel() { TableModel m = getModel(); if (m != null) { // Remove any current columns TableColumnModel cm = getColumnModel(); while (cm.getColumnCount() > 0) { cm.removeColumn(cm.getColumn(0)); } // Create new columns from the data model info for (int i = 0; i < m.getColumnCount(); i++) { TableColumn newColumn = new TableColumn(i); // Special renderer for supporting selection of a particular // column header newColumn.setHeaderRenderer(new DefaultTableSelectableCellRenderer()); addColumn(newColumn); } } }
private static void setColumnWidths(JTable table, MetricTableSpecification tableSpecification) { final TableModel model = table.getModel(); final TableColumnModel columnModel = table.getColumnModel(); final List<Integer> columnWidths = tableSpecification.getColumnWidths(); final List<String> columnOrder = tableSpecification.getColumnOrder(); if (columnWidths != null && !columnWidths.isEmpty()) { final int columnCount = model.getColumnCount(); for (int i = 0; i < columnCount; i++) { final String columnName = model.getColumnName(i); final int index = columnOrder.indexOf(columnName); if (index != -1) { final Integer width = columnWidths.get(index); final TableColumn column = columnModel.getColumn(i); column.setPreferredWidth(width.intValue()); } } } else { final Graphics graphics = table.getGraphics(); final Font font = table.getFont(); final FontMetrics fontMetrics = table.getFontMetrics(font); final int rowCount = model.getRowCount(); int maxFirstColumnWidth = 100; for (int i = 0; i < rowCount; i++) { final String name = (String) model.getValueAt(i, 0); if (name != null) { final Rectangle2D stringBounds = fontMetrics.getStringBounds(name, graphics); final double stringWidth = stringBounds.getWidth(); if (stringWidth > maxFirstColumnWidth) { maxFirstColumnWidth = (int) stringWidth; } } } final int allocatedFirstColumnWidth = Math.min(300, maxFirstColumnWidth + 5); final TableColumn column = columnModel.getColumn(0); column.setPreferredWidth(allocatedFirstColumnWidth); } }
/** * Return a label for the given point on the graph axis * * @param value the value on the graph * @return the label for the given value */ private String getLeafLabel(double value) { String label = Double.toString(value); try { int v = (int) value; int r = idxMap.getSrc(v); if (r < 0 || r >= tm.getRowCount()) { return ""; } if (labelColumn >= 0 && labelColumn < tm.getColumnCount()) { Object o = tm.getValueAt(r, labelColumn); return o != null ? o.toString() : ""; } } catch (Exception ex) { ExceptionHandler.popupException("" + ex); } try { label = Integer.toString((int) value); } catch (Exception ex) { ExceptionHandler.popupException("" + ex); } return label; }
private Object exportDelimited() { int delimIndex = delimCombo.getSelectedIndex(); char delim = 0; switch (delimIndex) { case 0: delim = '|'; break; case 1: delim = ','; break; case 2: delim = ';'; break; case 3: delim = '#'; break; case 4: delim = customDelimField.getText().charAt(0); break; } ResultsProgressDialog progressDialog = null; PrintWriter writer = null; File exportFile = null; try { exportFile = new File(fileNameField.getText()); StringBuilder rowLines = new StringBuilder(5000); writer = new PrintWriter(new FileWriter(exportFile, false), true); int rowCount = model.getRowCount(); int columnCount = model.getColumnCount(); progressDialog = progressDialog(rowCount); if (columnHeadersCheck.isSelected()) { for (int i = 0; i < columnCount; i++) { rowLines.append(model.getColumnName(i)); if (i != columnCount - 1) { rowLines.append(delim); } } writer.println(rowLines.toString()); rowLines.setLength(0); } boolean applyQuotes = applyQuotesCheck.isSelected(); for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { Object value = model.getValueAt(i, j); if (applyQuotes && isCDATA((RecordDataItem) value)) { rowLines.append("\"" + valueAsString(value) + "\""); } else { rowLines.append(valueAsString(value)); } if (j != columnCount - 1) { rowLines.append(delim); } } writer.println(rowLines.toString()); rowLines.setLength(0); progressDialog.increment(i + 1); } return "done"; } catch (IOException e) { return handleError(e); } finally { if (progressDialog != null && progressDialog.isVisible()) { progressDialog.dispose(); progressDialog = null; } if (writer != null) { writer.close(); } } }
/** * Contruct a component for a similarity line * * @param similarity * @param similarityString */ protected SimilarityTable(final Qualifier simQualifier, final DatabaseDocument doc) { this.origQualifiers = new QualifierVector(); this.origQualifiers.add(simQualifier); infoLevelButton.setOpaque(false); infoLevelButton.setHorizontalAlignment(SwingConstants.LEFT); tableData.setSize(NUMBER_COLUMNS); tableData.setElementAt(ORGANISM_COL, 0); tableData.setElementAt(HIT_COL, 1); tableData.setElementAt(HIT_DBXREF_COL, 2); tableData.setElementAt(DESCRIPTION_COL, 3); tableData.setElementAt(EVALUE_COL, 4); tableData.setElementAt(LENGTH_COL, 5); tableData.setElementAt(ID_COL, 6); tableData.setElementAt(QUERY_COL, 7); tableData.setElementAt(SUBJECT_COL, 8); tableData.setElementAt(SCORE_COL, 9); tableData.setElementAt(OVERLAP_COL, 10); tableData.setElementAt(METHOD_COL, 11); tableData.setElementAt(REMOVE_BUTTON_COL, 12); // add rows of similarity StringVector sims = simQualifier.getValues(); for (int i = 0; i < sims.size(); i++) rowData.add(getRowData((String) sims.get(i), tableData)); JTable similarityTable = new JTable(rowData, tableData); setTable(similarityTable); // set hand cursor similarityTable.addMouseMotionListener( new MouseMotionAdapter() { private Cursor handCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); public void mouseMoved(MouseEvent e) { int col = table.columnAtPoint(e.getPoint()); String colName = table.getColumnName(col); if (colName.equals(HIT_COL) || colName.equals(HIT_DBXREF_COL) || colName.equals(REMOVE_BUTTON_COL)) table.setCursor(handCursor); else table.setCursor(Cursor.getDefaultCursor()); } }); similarityTable.setColumnSelectionAllowed(false); similarityTable.setRowSelectionAllowed(true); packColumn(similarityTable, getColumnIndex(LENGTH_COL), 4); packColumn(similarityTable, getColumnIndex(EVALUE_COL), 4); packColumn(similarityTable, getColumnIndex(ID_COL), 4); packColumn(similarityTable, getColumnIndex(HIT_COL), 6); packColumn(similarityTable, getColumnIndex(HIT_DBXREF_COL), 6); final TableColumn[] hideColumns = new TableColumn[5]; hideColumns[0] = similarityTable.getColumn(QUERY_COL); hideColumns[1] = similarityTable.getColumn(SUBJECT_COL); hideColumns[2] = similarityTable.getColumn(SCORE_COL); hideColumns[3] = similarityTable.getColumn(OVERLAP_COL); hideColumns[4] = similarityTable.getColumn(METHOD_COL); for (int i = 0; i < hideColumns.length; i++) { hideColumns[i].setMinWidth(0); hideColumns[i].setMaxWidth(0); } infoLevelButton.addActionListener( new ActionListener() { private boolean show = true; public void actionPerformed(ActionEvent e) { // change the column size for (int i = 0; i < hideColumns.length; i++) { if (show) packColumn(getTable(), getColumnIndex((String) hideColumns[i].getHeaderValue()), 2); else { hideColumns[i].setMinWidth(0); hideColumns[i].setMaxWidth(0); } } show = !show; if (infoLevelButton.getText().equals("Details")) infoLevelButton.setText("Hide Details"); else infoLevelButton.setText("Details"); } }); TableModel tableModel = getTable().getModel(); // remove button column TableColumn col = getTable().getColumn(REMOVE_BUTTON_COL); col.setMinWidth(35); col.setMaxWidth(40); col.setPreferredWidth(40); final SimilarityRenderer renderer = new SimilarityRenderer(); for (int columnIndex = 0; columnIndex < tableModel.getColumnCount(); columnIndex++) { col = getTable().getColumnModel().getColumn(columnIndex); col.setCellRenderer(renderer); col.setCellEditor(new CellEditing(new JTextField())); } col = getTable().getColumn(HIT_COL); col.setCellEditor( new LinkEditor(new JCheckBox(), (DefaultTableModel) getTable().getModel(), null)); col = getTable().getColumn(HIT_DBXREF_COL); col.setCellEditor( new LinkEditor(new JCheckBox(), (DefaultTableModel) getTable().getModel(), null)); // remove JButton column col = getTable().getColumn(REMOVE_BUTTON_COL); col.setCellEditor( new ButtonEditor(new JCheckBox(), (DefaultTableModel) getTable().getModel(), "X", doc)); }
public void writeEmbedded(final PrintWriter pWriter) { if (isDataSet() && pWriter != null) { pWriter.write(getTableSegment("TableStart")); final String columnsDecl = getTableSegment("ColumnsDecl"); if (columnsDecl != null && columnsDecl.length() > 0) { final Format pattern = new MessageFormat(columnsDecl); final StringBuilder sBuilder = new StringBuilder(); final String singleColumnDecl = getTableSegment("SingleColumnDecl"); for (int col = 0; col < data.getColumnCount(); col++) { if (csm == null || csm.isSelectedIndex(col)) { sBuilder.append(singleColumnDecl); } } final Object[] holders = {sBuilder.toString()}; final String columnDeclarations = pattern.format(holders); pWriter.write(columnDeclarations); } int lastCol = 0; for (int col = 0; col < data.getColumnCount(); col++) { if (csm == null || csm.isSelectedIndex(col)) { lastCol = col; } } final String headerDelimiter = getTableSegment("HeaderDelimiter"); pWriter.write(getTableSegment("HeaderRowStart")); for (int col = 0; col < data.getColumnCount(); col++) { if (csm == null || csm.isSelectedIndex(col)) { String columnName = data.getColumnName(col); if (columnName != null && columnName.indexOf(headerDelimiter) != -1) { columnName = '\"' + columnName + '\"'; } pWriter.write(columnName); if (col == lastCol) { pWriter.println(); } else { pWriter.write(headerDelimiter); } } } pWriter.write(getTableSegment("HeaderRowEnd")); final String rowStart = getTableSegment("RowStart"); final String rowEnd = getTableSegment("RowEnd"); final String delimiter = getTableSegment("Delimiter"); for (int row = 0; row < data.getRowCount(); row++) { if (lsm == null || lsm.isSelectedIndex(row)) { pWriter.write(rowStart); for (int col = 0; col < data.getColumnCount(); col++) { if (csm == null || csm.isSelectedIndex(col)) { final Object cellObject = data.getValueAt(row, col); String cellString = (cellObject == null ? null : cellObject.toString()); if (cellString != null && cellString.indexOf(delimiter) != -1) { cellString = '\"' + cellString + '\"'; } pWriter.write(cellString == null ? nullEntry : cellString); if (col == lastCol) { pWriter.println(); } else { pWriter.write(delimiter); } } } pWriter.write(rowEnd); } } pWriter.write(getTableSegment("TableEnd")); } }
public int getColumnCount() { return columnCountLimit == null ? original.getColumnCount() : columnCountLimit; }
/** * Creates new form OutputIntermedTable. * * @param intermed DOCUMENT ME! * @param enclosingChars DOCUMENT ME! */ public OutputIntermedTable(final TableModel intermed, final String[] enclosingChars) { initComponents(); deduplicate = new boolean[intermed.getColumnCount()]; if ((enclosingChars != null) && (enclosingChars.length == intermed.getColumnCount())) { for (int i = 0; i < intermed.getColumnCount(); ++i) { deduplicate[i] = "'".equals(enclosingChars[i]); } } else { Arrays.fill(deduplicate, false); } tblIntermed.setFont(new java.awt.Font("Dialog", 0, 12)); this.tblIntermed.setModel(intermed); this.tblIntermed .getSelectionModel() .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); this.tblIntermed.setCellSelectionEnabled(true); setName(intermed.toString()); lblRowCount.setText("Rows: " + intermed.getRowCount()); TableSortDecorator.decorate(tblIntermed); final DefaultTableCellRenderer r = new DefaultTableCellRenderer() { @Override public final Component getTableCellRendererComponent( final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { final Component c; if (value != null) { // hardcoded unescaping for performance final char[] chars = value.toString().toCharArray(); final char[] res; if ((chars.length > 1) && deduplicate[column]) { res = new char[chars.length]; int ptr = -1; char cur = chars[0]; char next; for (int j = 0; j < (chars.length - 1); ++j) { next = chars[j + 1]; if ((cur == '\'') && (next == '\'')) { ++j; } res[++ptr] = cur; cur = next; } res[++ptr] = chars[chars.length - 1]; c = super.getTableCellRendererComponent( table, new String(res, 0, ++ptr), isSelected, hasFocus, row, column); } else { c = super.getTableCellRendererComponent( table, new String(chars, 0, chars.length), isSelected, hasFocus, row, column); } c.setForeground(Color.BLACK); } else { c = super.getTableCellRendererComponent( table, NULL, isSelected, hasFocus, row, column); // c.setBackground(Color.WHITE); c.setForeground(Color.LIGHT_GRAY); } return c; } }; // tblIntermed.setDefaultRenderer(String.class, r); tblIntermed.setDefaultRenderer(Object.class, r); }
public static void main(String[] args) throws Exception { TableModel result = new SampleDataGenerator().generate(); System.out.println("Columns -> " + result.getColumnCount()); System.out.println("Rows -> " + result.getRowCount()); }
public int getColumnCount() { return (myModel == null) ? 0 : myModel.getColumnCount(); }
public void tableChanged(TableModelEvent e) { setColumnCount(sourceModel.getColumnCount()); }
public int getColumnCount() { return ((model == null) ? 0 : model.getColumnCount()); }
private Object exportExcel() { OutputStream outputStream = null; ResultsProgressDialog progressDialog = null; try { outputStream = createOutputStream(); ExcelWorkbookBuilder builder = createExcelWorkbookBuilder(); builder.createSheet("Result Set Export"); int rowCount = model.getRowCount(); int columnCount = model.getColumnCount(); progressDialog = progressDialog(rowCount); List<String> values = new ArrayList<String>(columnCount); if (columnHeadersCheck.isSelected()) { for (int i = 0; i < columnCount; i++) { values.add(model.getColumnName(i)); } builder.addRowHeader(values); } for (int i = 0; i < rowCount; i++) { values.clear(); for (int j = 0; j < columnCount; j++) { Object value = model.getValueAt(i, j); values.add(valueAsString(value)); } builder.addRow(values); progressDialog.increment(i + 1); } builder.writeTo(outputStream); return "done"; } catch (IOException e) { return handleError(e); } finally { if (progressDialog != null && progressDialog.isVisible()) { progressDialog.dispose(); progressDialog = null; } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } } }
public int getColumnCount() { return (tableModel == null) ? 0 : tableModel.getColumnCount(); }
/** * Construct Statements based on given TableModel. * * @param tableModel given TableModel * @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); if (tableModel.getColumnClass(i).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); } 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); if (tableModel.getColumnClass(j).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.getCode().toString(), code_string)); atoms.add(new Atom(stock.getSymbol().toString(), symbol_string)); } else if (tableModel.getColumnClass(j).equals(Date.class)) { DateFormat dateFormat = org.yccheok.jstock.gui.Utils.getCommonDateFormat(); atoms.add( new Atom(object != null ? dateFormat.format(((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); } return s; }