List of usage examples for javax.swing.table TableModel getColumnCount
public int getColumnCount();
From source file:pt.webdetails.cda.utils.TableModelUtils.java
private static List<Integer> getOutputIndexes(final DataAccess dataAccess, final QueryOptions queryOptions, TableModel table) throws InvalidOutputIndexException { // First we need to check if there's nothing to do. ArrayList<Integer> outputIndexes = dataAccess.getOutputs(queryOptions.getOutputIndexId()); if (outputIndexes == null) { throw new InvalidOutputIndexException("Invalid outputIndexId: " + queryOptions.getOutputIndexId(), null);/*w w w . j ava 2 s. c o m*/ } /* if (queryOptions.isPaginate() == false && outputIndexes.isEmpty() && queryOptions.getSortBy().isEmpty()) { // No, the original one is good enough return t; } */ // 2 // If output mode == exclude, we need to translate the excluded outputColuns // into included ones if (dataAccess.getOutputMode(queryOptions.getOutputIndexId()) == DataAccess.OutputMode.EXCLUDE && outputIndexes.size() > 0) { ArrayList<Integer> newOutputIndexes = new ArrayList<Integer>(); for (int i = 0; i < table.getColumnCount(); i++) { if (!outputIndexes.contains(i)) { newOutputIndexes.add(i); } } outputIndexes = newOutputIndexes; } return outputIndexes; }
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);//w ww. ja va 2s . c om 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 # *//*from w ww.j a va 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; }
From source file:uk.ac.babraham.SeqMonk.Filters.GeneSetFilter.GeneSetDisplay.java
public void actionPerformed(ActionEvent ae) { /* if (ae.getActionCommand().equals("plot")) { //from w ww .ja va2 s . c o m drawScatterPlot(); } */ if (ae.getActionCommand().equals("save_image")) { ImageSaver.saveImage(scatterPlotPanel); } else if (ae.getActionCommand().equals("swap_plot")) { if (storesQuantitated()) { plotPanel.remove(scatterPlotPanel); if (scatterPlotPanel instanceof GeneSetScatterPlotPanel) { scatterPlotPanel = new ZScoreScatterPlotPanel(fromStore, toStore, probes, currentSelectedProbeList, dotSizeSlider.getValue(), zScoreLookupTable); plotPanel.add(scatterPlotPanel, BorderLayout.CENTER); swapPlotButton.setText("Display standard scatterplot"); } else if (scatterPlotPanel instanceof ZScoreScatterPlotPanel) { scatterPlotPanel = new GeneSetScatterPlotPanel(fromStore, toStore, startingProbeList, currentSelectedProbeList, true, dotSizeSlider.getValue(), customRegressionValues, simpleRegression); plotPanel.add(scatterPlotPanel, BorderLayout.CENTER); swapPlotButton.setText("Display z-score plot"); } } } else if (ae.getActionCommand().equals("close")) { /* if(currentSelectedProbeList != null){ currentSelectedProbeList[0].delete(); //currentSelectedProbeList = null; } */ this.dispose(); } else if (ae.getActionCommand().equals("select_all")) { if (selectAllButton.isSelected()) { for (int i = 0; i < tableModel.selected.length; i++) { tableModel.selected[i] = true; tableModel.fireTableCellUpdated(i, 0); } selectAllButton.setText("deselect all"); } else { for (int i = 0; i < tableModel.selected.length; i++) { tableModel.selected[i] = false; tableModel.fireTableCellUpdated(i, 0); } selectAllButton.setText("select all"); } } else if (ae.getActionCommand().equals("save_selected_probelists")) { boolean[] selectedListsBoolean = tableModel.selected; if (selectedListsBoolean.length != filterResultsPVals.length) { System.err.println("not adding up here"); } else { ArrayList<MappedGeneSetTTestValue> selectedListsArrayList = new ArrayList<MappedGeneSetTTestValue>(); for (int i = 0; i < selectedListsBoolean.length; i++) { if (selectedListsBoolean[i] == true) { selectedListsArrayList.add(filterResultsPVals[i]); } } MappedGeneSetTTestValue[] selectedLists = selectedListsArrayList .toArray(new MappedGeneSetTTestValue[0]); if (selectedLists.length == 0) { JOptionPane.showMessageDialog(SeqMonkApplication.getInstance(), "No probe lists were selected", "No probe lists selected", JOptionPane.INFORMATION_MESSAGE); return; } saveProbeLists(selectedLists); if (currentSelectedProbeList != null) { currentSelectedProbeList[0].delete(); currentSelectedProbeList = null; } } } else if (ae.getActionCommand().equals("save_table")) { JFileChooser chooser = new JFileChooser(SeqMonkPreferences.getInstance().getSaveLocation()); chooser.setMultiSelectionEnabled(false); chooser.setFileFilter(new FileFilter() { public String getDescription() { return "Text files"; } public boolean accept(File f) { if (f.isDirectory() || f.getName().toLowerCase().endsWith(".txt")) { return true; } else { return false; } } }); int result = chooser.showSaveDialog(this); if (result == JFileChooser.CANCEL_OPTION) return; File file = chooser.getSelectedFile(); if (!file.getPath().toLowerCase().endsWith(".txt")) { file = new File(file.getPath() + ".txt"); } SeqMonkPreferences.getInstance().setLastUsedSaveLocation(file); // Check if we're stepping on anyone's toes... if (file.exists()) { int answer = JOptionPane.showOptionDialog(this, file.getName() + " exists. Do you want to overwrite the existing file?", "Overwrite file?", 0, JOptionPane.QUESTION_MESSAGE, null, new String[] { "Overwrite and Save", "Cancel" }, "Overwrite and Save"); if (answer > 0) { return; } } try { PrintWriter p = new PrintWriter(new FileWriter(file)); TableModel model = table.getModel(); int rowCount = model.getRowCount(); int colCount = model.getColumnCount(); // Do the headers first StringBuffer b = new StringBuffer(); for (int c = 1; c < colCount; c++) { b.append(model.getColumnName(c)); if (c + 1 != colCount) { b.append("\t"); } } p.println(b); for (int r = 0; r < rowCount; r++) { b = new StringBuffer(); for (int c = 1; c < colCount; c++) { b.append(model.getValueAt(r, c)); if (c + 1 != colCount) { b.append("\t"); } } p.println(b); } p.close(); } catch (FileNotFoundException e) { new CrashReporter(e); } catch (IOException e) { new CrashReporter(e); } } else { throw new IllegalArgumentException("Unknown command " + ae.getActionCommand()); } }
From source file:us.daveread.basicquery.BasicQuery.java
/** * Gets each cell of the selected row - if the object stored in the cell * is of type java.sql.Blob, the object is written to disk by calling * writeBlob(String, java.sql.Blob) on the DB connection. *//*from w w w.j a v a 2 s .co m*/ private void saveBLOBs() { TableModel model; int selectedRow; String filesWritten; if (table.getSelectedRowCount() != 1) { userMessage(Resources.getString("errChooseOneRowText"), Resources.getString("errChooseOneRowTitle"), JOptionPane.ERROR_MESSAGE); } else { model = table.getModel(); selectedRow = table.getSelectedRow(); filesWritten = ""; for (int col = 1; col < model.getColumnCount(); col++) { if (model.getValueAt(selectedRow, col) instanceof java.sql.Blob) { LOGGER.debug("Blob[" + (java.sql.Blob) model.getValueAt(selectedRow, col) + "]"); filesWritten += writeBlob(model.getColumnName(col), (java.sql.Blob) model.getValueAt(selectedRow, col)) + "\n"; } } userMessage(Resources.getString("msgBLOBWrittenText", filesWritten), Resources.getString("msgBLOBWrittenTitle"), JOptionPane.INFORMATION_MESSAGE); } }
From source file:us.daveread.basicquery.BasicQuery.java
/** * Gets the column name for the column that is being selected in the table * /* ww w . ja v a 2 s .co m*/ * @return columns A string array with the Column Names and Values */ private String[][] getColumnNamesForTable() { String[][] columns; TableModel model; model = table.getModel(); if (modeOfCurrentTable == Query.MODE_DESCRIBE) { columns = new String[model.getRowCount()][3]; for (int i = 0; i < model.getRowCount(); ++i) { columns[i][0] = model.getValueAt(i, 0).toString(); columns[i][1] = model.getValueAt(i, 1).toString(); // Type if (table.isRowSelected(i)) { columns[i - 1][2] = "Selected"; } else { columns[i - 1][2] = null; } } } else { columns = new String[model.getColumnCount()][3]; for (int i = 0; i < model.getColumnCount(); ++i) { columns[i][0] = model.getColumnName(i); // Remove type if present if (columns[i][0].indexOf("[") > -1) { columns[i][1] = columns[i][0].substring(columns[i][0].indexOf("[") + 1); columns[i][0] = columns[i][0].substring(0, columns[i][0].indexOf("[")).trim(); } else { /** * Todo: change column name/type design so that we can easily get the * column type. */ columns[i][1] = "Number"; } if (table.isColumnSelected(i)) { columns[i][2] = "Selected"; } else { columns[i][2] = null; } } } return columns; }
From source file:us.daveread.basicquery.BasicQuery.java
/** * Writes the data onto a file that is specified by the filePath * // w w w . ja va2 s .c o m * @param query * The SQL statement * @param model * The model for the current results * @param filePath * A String that denotes the filepath * @param append * Whether to append the current results into the file * * @todo Make this handle other data types (especially Date/Time) better * for cleaner import to spreadsheet. */ private void writeDataAsCSV(String query, TableModel model, String filePath, boolean append) { PrintWriter out; int row, col; boolean[] quote; boolean quoteThis; String temp; Object value; out = null; this.setCursor(new Cursor(Cursor.WAIT_CURSOR)); (flashRunIndicator = new Thread( new FlashForeground(runIndicator, Color.red.brighter(), Color.lightGray, 5))).start(); (timeRunIndicator = new Thread(new InsertTime(timeIndicator, new java.util.Date().getTime(), QUERY_EXECUTION_TIMER_UPDATE_DELAY_MS))).start(); try { out = new PrintWriter(new FileWriter(filePath, append)); messageOut(""); messageOut(Resources.getString("msgStartExportToFile", filePath)); // Output query if (!fileExportsRaw.isSelected()) { // Make it look like a comment using hash comment character out.print("#,"); out.print("\""); } // out.print(getQuery().getSQL()); out.print(query.replaceAll("\n", " ")); if (!fileExportsRaw.isSelected()) { out.print("\""); } out.println(); // Setup array to hold which columns need to be quoted quote = new boolean[model.getColumnCount()]; // Output column headings - determine if column needs quotes for (col = 0; col < model.getColumnCount(); ++col) { if (col > 0) { out.print(","); } out.print("\"" + model.getColumnName(col) + "\""); /** * todo: use column type to set need for quotes */ quote[col] = false; } out.println(); // Output data for (row = 0; row < model.getRowCount(); ++row) { for (col = 0; col < model.getColumnCount(); ++col) { if (col > 0) { out.print(","); } // Get the field content try { value = model.getValueAt(row, col); if (value == null) { temp = ""; } else if (value instanceof java.sql.Timestamp) { temp = Utility.formattedDate((java.sql.Timestamp) value); } else { temp = model.getValueAt(row, col).toString(); if (!fileExportsRaw.isSelected()) { temp = temp.replace('"', '\''); temp = temp.replace('\n', '~'); } } } catch (Exception any) { LOGGER.error("Failed to export data", any); // Display error and move on messageOut(Resources.getString("errFailDuringExport", any.getMessage()), STYLE_RED); temp = ""; } // Decide if quotes are needed: // -If the row is a known character type // -If this field contains a comma quoteThis = !fileExportsRaw.isSelected() && (quote[col] || temp.indexOf(",") > -1); // Output the field if (quoteThis) { out.print("\""); } out.print(temp); if (quoteThis) { out.print("\""); } } if (!fileNoCRAddedToExportRows.isSelected()) { out.println(); } } // Assume that if writing multiple resultsets to file the // user would appreciate a separation line between them. if (append) { out.println("\n********"); } messageOut(Resources.getString("msgEndExportToFile")); } catch (Exception any) { LOGGER.error("Unable to write data to file", any); messageOut(Resources.getString("errFailDataSave", any.toString()), STYLE_RED); } finally { if (out != null) { try { out.close(); } catch (Exception any) { LOGGER.error("Failed while writing data to CSV file", any); } } } flashRunIndicator.interrupt(); flashRunIndicator = null; timeRunIndicator.interrupt(); timeRunIndicator = null; this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); }
From source file:us.daveread.basicquery.BasicQuery.java
/** * Writes the data onto a file that is specified by the filePath * This version writes the data from the ResultSet instance * so that the results do not need to be loaded into memory. * // www. j a v a2s . c o m * @param query * The SQL statement for the current data * @param model * The model for the current data * @param filePath * A String that denotes the filepath * @param result * The result set for the query * @param myType * The data type ids for the columns in the result set * @param append * Whether to append the data in the file * * @todo Make this handle other data types (especially Date/Time) better * for cleaner import to spreadsheet. */ private void writeDataAsCSV(String query, TableModel model, String filePath, ResultSet result, int[] myType, boolean append) { PrintWriter out; int row, col; boolean[] quote; boolean quoteThis; String temp; Object value; out = null; /* * this.setCursor(new Cursor(Cursor.WAIT_CURSOR)); * (flashRunIndicator = new Thread(new FlashForeground(runIndicator, * Color.red.brighter(), Color.lightGray, 5))).start(); * (timeRunIndicator = new Thread(new InsertTime(timeIndicator, * new java.util.Date().getTime(), * 250))).start(); */ try { out = new PrintWriter(new FileWriter(filePath, append)); messageOut(""); messageOut(Resources.getString("msgStartExportToFile", filePath)); // Output query if (!fileExportsRaw.isSelected()) { // Make it look like a comment using hash comment character out.print("#,"); out.print("\""); } // out.print(getQuery().getSQL()); out.print(query.replaceAll("\n", " ")); if (!fileExportsRaw.isSelected()) { out.print("\""); } out.println(); // Setup array to hold which columns need to be quoted quote = new boolean[model.getColumnCount()]; // Output column headings - determine if column needs quotes for (col = 0; col < model.getColumnCount(); ++col) { if (col > 0) { out.print(","); } out.print("\"" + model.getColumnName(col) + "\""); /** * todo: use column type to set need for quotes */ quote[col] = false; } out.println(); // Output data row = 0; while (result.next()) { if (row % RESULT_PROCESSING_ROWS_PER_STATUS_MESSAGE == 0) { messageOut("" + row, STYLE_SUBTLE); } for (col = 0; col < model.getColumnCount(); ++col) { if (col > 0) { out.print(","); } // Get the field content value = getResultField(result, col + 1, myType[col]); try { if (value == null) { temp = ""; } else if (value instanceof java.sql.Timestamp) { temp = Utility.formattedDate((java.sql.Timestamp) value); } else { temp = value.toString(); if (!fileExportsRaw.isSelected()) { temp = temp.replace('"', '\''); temp = temp.replace('\n', '~'); } } } catch (Exception any) { LOGGER.error("Failed to export data", any); // Display error and move on messageOut(Resources.getString("errFailDuringExport", any.getMessage()), STYLE_RED); temp = ""; } // Decide if quotes are needed: // -If the row is a known character type // -If this field contains a comma quoteThis = !fileExportsRaw.isSelected() && (quote[col] || temp.indexOf(",") > -1); // Output the field if (quoteThis) { out.print("\""); } out.print(temp); if (quoteThis) { out.print("\""); } } if (!fileNoCRAddedToExportRows.isSelected()) { out.println(); } ++row; } // Assume that if writing multiple resultsets to file the // user would appreciate a separation line between them. if (append) { out.println("\n********"); } messageOut(Resources.getString("msgEndExportToFile")); } catch (Exception any) { LOGGER.error("Unable to write data to file", any); messageOut(Resources.getString("errFailDataSave", any.toString()), STYLE_RED); } finally { if (out != null) { try { out.close(); } catch (Exception any) { LOGGER.error("Failed while writing data to CSV file", any); } } } /* * flashRunIndicator.interrupt(); * flashRunIndicator = null; * timeRunIndicator.interrupt(); * timeRunIndicator = null; * this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); */ }
From source file:vacationscheduler.UpcomingReservations.java
public void jTableToExcel() { try {//from w w w . j a va2 s . c om String fileName = "./excelAttempt.xls"; TableModel model = jtable_upcomingReservations.getModel(); FileWriter file = new FileWriter(fileName); for (int column = 0; column < model.getColumnCount(); column++) { file.write(model.getColumnName(column) + "\t"); } file.write("\n"); for (int i = 0; i < model.getRowCount(); i++) { for (int j = 0; j < model.getColumnCount(); j++) { file.write(model.getValueAt(i, j).toString() + "\t"); } file.write("\n"); } file.close(); File file_file = new File(fileName); Desktop.getDesktop().open(file_file); } catch (IOException ex) { Logger.getLogger(UpcomingReservations.class.getName()).log(Level.SEVERE, null, ex); } }