List of usage examples for javax.swing.table TableModel getValueAt
public Object getValueAt(int rowIndex, int columnIndex);
columnIndex
and rowIndex
. From source file:pt.webdetails.cda.tests.KettleStringArrayParamIT.java
public void testKettleStringArray() throws Exception { final CdaSettings cdaSettings = parseSettingsFile("sample-kettle-ParamArray.cda"); final QueryOptions queryOptions = new QueryOptions(); queryOptions.setDataAccessId("1"); queryOptions.setParameter("countries", "Portugal;Germany"); queryOptions.setParameter("Costumers", "307;369"); logger.info("Doing query"); TableModel tm = doQuery(cdaSettings, queryOptions); assertEquals(2, tm.getRowCount());// www . jav a 2 s . co m assertEquals("307", tm.getValueAt(0, 0).toString()); assertEquals("Der Hund Imports", tm.getValueAt(0, 1)); }
From source file:pt.webdetails.cda.utils.DataTableFilter.java
private String[] getRelevantColumns(TableModel table, int rowIndex) { String[] row = new String[searchableColumns.length]; for (int i = 0; i < row.length; i++) { Object rawValue = table.getValueAt(rowIndex, searchableColumns[i]); row[i] = (rawValue == null) ? null : rawValue.toString(); }//from www . j a v a 2 s .co m return row; }
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 ww . j a v a 2 s . c o m // 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 ww . j ava2s .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 ww .j a v a2 s . co 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 # *///from ww w . j a v a 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:sms.Form1Exams.java
private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked int a = 0;/*from www. j a va2 s . co m*/ cntrltbl = 1; int index = jComboBoxSubjects.getSelectedIndex(); if (index != 0) { int i = this.table.getSelectedRow(); TableModel model = this.table.getModel(); lblsubject.setText(subjectin); subjectup.setEditable(true); this.subjectup.setText(model.getValueAt(i, index + 1).toString()); uniqn = (model.getValueAt(i, 1).toString()); // String []subs=findSubjectname(); // for(int i=0;i<subs.length;i++){ // if(subjectin.equals(subs[i])){ // // JOptionPane.showMessageDialog(null, subjects[i]); // a=i+2; // handleTableMouseEvent(a); // } // } } }
From source file:sms.Form1Exams.java
public String handleTableMouseEvent() { int index = jComboBoxSubjects.getSelectedIndex(); int i = this.table.getSelectedRow(); TableModel model = this.table.getModel(); lblsubject.setText(subjectin);//from w w w . ja v a2s . c o m this.subjectup.setText(model.getValueAt(i, index).toString()); uniqn = (model.getValueAt(i, 1).toString()); return uniqn; }
From source file:uk.ac.babraham.SeqMonk.Filters.GeneSetFilter.GeneSetDisplay.java
public void actionPerformed(ActionEvent ae) { /* if (ae.getActionCommand().equals("plot")) { /*from w ww . j av a 2s . 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
/** * Reports statistics on various data such as the date a query was executed * and//from w w w . j a va2s .co m * the date the results were fetched. Other statistics are reported on such as * the * the date a connection was asked for, and the date it was actually received. * The report statistics are written to an external text file * represented by DBSTATS_NAME. * * @param sqlStatement * The SQL statement * @param connAsk * The time when the connection was requested * @param connGot * The time when the connection was returned * @param stmtGot * The time when the statement was returned * @param queryStart * The time when query exeution began * @param queryReady * The time when the query finished exeuting * @param queryRSFetched * The time when the result set had been completely fetched * @param queryRSProcessed * The time when the result set had been completely processed * @param rows * The number of rows in the result set * @param cols * The number of columns in the result set * @param model * The table model for the results * @param outParams * The output parameters defined for this SQL statement */ private void reportStats(String sqlStatement, java.util.Date connAsk, java.util.Date connGot, java.util.Date stmtGot, java.util.Date queryStart, java.util.Date queryReady, java.util.Date queryRSFetched, java.util.Date queryRSProcessed, long rows, int cols, TableModel model, List<Object> outParams) { Runtime runtime; String runStats; PrintWriter out; boolean firstEntry; final String valueNotApplicable = "\"" + Resources.getString("proValueNotApplicable") + "\","; runStats = ""; out = null; firstEntry = false; if (fileLogStats.isSelected()) { // Identify whether file exists, if not create and add header row try { new FileReader(DBSTATS_NAME).close(); } catch (Exception any) { firstEntry = true; } try { out = new PrintWriter(new FileWriter(DBSTATS_NAME, true)); } catch (Exception any) { LOGGER.error("Failed to write the statistics file [" + DBSTATS_NAME + "]", any); messageOut(Resources.getString("errFailWriteStatsFile", DBSTATS_NAME, any.getMessage()), STYLE_RED); } } // Make sure it is always safe to write to "out" -- simplifies logic if (out == null) { out = new PrintWriter(new StringWriter()); } // Header, if needed if (firstEntry) { out.print(Resources.getString("proQueryStatsExportHeader")); if (outParams != null && outParams.size() > 0) { for (int param = 0; param < outParams.size(); ++param) { out.print(Resources.getString("proQueryStatsExportHeaderParam", param + "")); } } out.println(); } // Output Query Index Number out.print(querySelection.getSelectedIndex() + ","); // Output SQL, replacing quotes with apostrophes out.print("\"" + sqlStatement.replace('"', '\'') + "\","); // Output timestamp out.print(Utility.formattedDate(new java.util.Date()) + ","); // Output time required to get connection to database if (connAsk != null && connGot != null) { runStats += Resources.getString("proTimeConnOpen", (connGot.getTime() - connAsk.getTime()) + ""); runStats += " "; out.print((connGot.getTime() - connAsk.getTime()) + ","); } else { out.print(valueNotApplicable); } // Output time required to get statement object if (connGot != null && stmtGot != null) { runStats += Resources.getString("proTimeStmtAccess", (stmtGot.getTime() - connGot.getTime()) + ""); runStats += " "; out.print((stmtGot.getTime() - connGot.getTime()) + ","); } else { out.print(valueNotApplicable); } // Time it took to configure statement if (queryStart != null && stmtGot != null) { runStats += Resources.getString("proTimeStmtSetup", (queryStart.getTime() - stmtGot.getTime()) + ""); runStats += " "; out.print((queryStart.getTime() - stmtGot.getTime()) + ","); } else { out.print(valueNotApplicable); } runStats += "\n "; // Output time DB took to execute query if (queryStart != null && queryReady != null) { runStats += Resources.getString("proTimeDBExecute", (queryReady.getTime() - queryStart.getTime()) + ""); runStats += " "; out.print((queryReady.getTime() - queryStart.getTime()) + ","); } else { out.print(valueNotApplicable); } // Output time it took to fetch all results if (queryReady != null && queryRSFetched != null) { runStats += Resources.getString("proTimeResultsFetch", (queryRSFetched.getTime() - queryReady.getTime()) + ""); runStats += " "; out.print((queryRSFetched.getTime() - queryReady.getTime()) + ","); } else { out.print(valueNotApplicable); } // Output time it took to process all results if (queryReady != null && queryRSProcessed != null) { runStats += Resources.getString("proTimeResultSet", (queryRSProcessed.getTime() - queryReady.getTime()) + ""); runStats += " "; out.print((queryRSProcessed.getTime() - queryReady.getTime()) + ","); } else { out.print(valueNotApplicable); } if (runStats.length() > 0) { messageOut(Resources.getString("proTimeDBStats") + " ", STYLE_SUBTLE, false); messageOut(runStats, STYLE_NORMAL, false); runStats = ""; } // Output total time it took to obtain connection, execute SQL and obtain // results if (connAsk != null && queryRSFetched != null) { runStats += Resources.getString("proTimeTotal", (queryRSFetched.getTime() - connAsk.getTime()) + ""); runStats += " "; out.print((queryRSFetched.getTime() - connAsk.getTime()) + ","); } else if (connAsk != null && queryRSProcessed != null) { runStats += Resources.getString("proTimeTotal", (queryRSProcessed.getTime() - connAsk.getTime()) + ""); runStats += " "; out.print((queryRSProcessed.getTime() - connAsk.getTime()) + ","); } else if (connAsk != null && queryReady != null) { runStats += Resources.getString("proTimeTotal", (queryReady.getTime() - connAsk.getTime()) + ""); runStats += " "; out.print((queryReady.getTime() - connAsk.getTime()) + ","); } else { out.print(valueNotApplicable); } messageOut(runStats, STYLE_BOLD, true); // Output number of columns in resultset out.print(cols + ","); // Output number of rows returned or modified out.print(rows + "," + maxRows.getSelectedItem().toString() + ","); runtime = Runtime.getRuntime(); // Output environment information out.print(runtime.totalMemory() + "," + runtime.freeMemory() + "," + (runtime.totalMemory() - runtime.freeMemory()) + "," + runtime.maxMemory() + "," + runtime.availableProcessors()); if (configDisplayClientInfo.isSelected()) { runStats = Resources.getString("proMemAlloc", runtime.totalMemory() + ""); runStats += " " + Resources.getString("proMemFree", runtime.freeMemory() + ""); runStats += " " + Resources.getString("proMemUsed", (runtime.totalMemory() - runtime.freeMemory()) + ""); runStats += " " + Resources.getString("proMemMax", runtime.maxMemory() + ""); runStats += " " + Resources.getString("proProcessors", runtime.availableProcessors() + ""); messageOut(Resources.getString("proClientEnv") + " ", STYLE_SUBTLE, false); messageOut(runStats); } if (poolConnect.isSelected()) { messageOut(Resources.getString("msgPoolStats") + " ", STYLE_SUBTLE, false); messageOut(Resources.getString("msgPoolStatsCount", getDBPool().getNumActive() + "", getDBPool().getNumIdle() + "")); } // If output parameters, list them if (outParams != null && outParams.size() > 0) { for (int param = 0; param < outParams.size(); ++param) { out.print(","); if (outParams.get(param) instanceof String) { out.print("\""); } out.print(outParams.get(param)); if (outParams.get(param) instanceof String) { out.print("\""); } } } // If model given, output describe content if (model != null) { for (int row = 1; row < model.getRowCount(); ++row) { out.print(",\""); // Column Name out.print(model.getValueAt(row, 0)); // Type out.print(" " + model.getValueAt(row, 1)); // Size out.print(" " + model.getValueAt(row, 2)); // Precision out.print(" (" + model.getValueAt(row, 3) + "," + model.getValueAt(row, 4) + ")"); out.print("\""); } } out.println(); out.close(); }