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;
  }
Ejemplo n.º 2
0
 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);
     }
   }
 }
Ejemplo n.º 3
0
  /**
   * 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();
    }
  }
Ejemplo n.º 4
0
  private void jButton1ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed

    JFrame frame = new JFrame();
    int result =
        JOptionPane.showConfirmDialog(
            frame,
            TIMSMessages.DELETE_CONFIRMATION,
            TIMSMessages.DELETE_CONFIRMATION_TITLE,
            JOptionPane.YES_NO_OPTION);
    if (result == JOptionPane.YES_OPTION) {
      TableModel model = bransTB.getModel();
      ArrayList<Integer> brandsIds = new ArrayList<Integer>();
      for (int i = 0; i < model.getRowCount(); i++) {
        Boolean selected = (Boolean) model.getValueAt(i, 0);
        if (selected) {
          brandsIds.add((Integer) model.getValueAt(i, 1));
        }
      }
      DeleteBransController dbc = new DeleteBransController();
      dbc.setBrandIds(brandsIds);
      int count = dbc.deleteBrands();
      if (count > 0) {
        JOptionPane.showMessageDialog(null, count + TIMSMessages.BRANDS_DELETE_SUCCESS);
      } else {
        JOptionPane.showMessageDialog(null, TIMSMessages.BRANDS_DELETE_FAIL);
      }
      ViewBrandController brandController = new ViewBrandController();
      brandController.execute();
    }
  } // GEN-LAST:event_jButton1ActionPerformed
  protected static Building[] getBuildings(JTable buildingsJTable) {
    TableModel tableModel = buildingsJTable.getModel();

    ArrayList<Building> ret = new ArrayList();

    for (int i = 0; i < tableModel.getRowCount(); i++) {
      if ((boolean) tableModel.getValueAt(i, 0)) ret.add((Building) tableModel.getValueAt(i, 1));
    }

    if (ret.isEmpty()) {
      for (int i = 0; i < tableModel.getRowCount(); i++) {
        ret.add((Building) tableModel.getValueAt(i, 1));
      }
    }

    return ret.toArray(new Building[ret.size()]);
  }
Ejemplo n.º 6
0
  /**
   * Добавить данные из другой таблицы
   *
   * @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;
  }
  @Test
  public void testMaxRows() throws Exception {
    Table table = dataContext.getDefaultSchema().getTableByName(peopleIndexType);
    Query query = new Query().from(table).select(table.getColumns()).setMaxRows(5);
    DataSet dataSet = dataContext.executeQuery(query);

    TableModel tableModel = new DataSetTableModel(dataSet);
    assertEquals(5, tableModel.getRowCount());
  }
Ejemplo n.º 8
0
 public List<String> getSeletedTabs() {
   // TODO add your handling code here:
   TableModel model = dbTab.getModel();
   for (int i = 0; i < model.getRowCount(); i++) {
     Boolean b = (Boolean) model.getValueAt(i, 0);
     if (b != null && b.booleanValue()) selectedTabs.add(model.getValueAt(i, 1).toString());
   }
   return selectedTabs;
 }
Ejemplo n.º 9
0
 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);
     }
   }
 }
Ejemplo n.º 10
0
 private void jButton1ActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed
   // TODO add your handling code here:
   TableModel model = dbTab.getModel();
   for (int i = 0; i < model.getRowCount(); i++) {
     Boolean b = (Boolean) model.getValueAt(i, 0);
     if (b.booleanValue()) selectedTabs.add(model.getValueAt(i, 1).toString());
   }
   this.dispose();
 } // GEN-LAST:event_jButton1ActionPerformed
Ejemplo n.º 11
0
 @Override
 public void setModel(@NotNull TableModel model) {
   super.setModel(model);
   // initialize sizes once, when the real non-empty model is set
   if (!myColumnsSizeInitialized && model.getRowCount() > 0) {
     myColumnsSizeInitialized = true;
     setColumnPreferredSize();
     setAutoCreateColumnsFromModel(
         false); // otherwise sizes are recalculated after each TableColumn re-initialization
   }
 }
 @Nullable
 public GraphPrintCell getGraphPrintCellForRow(TableModel model, int rowIndex) {
   if (rowIndex >= model.getRowCount()) {
     return null;
   }
   Object commitValue = model.getValueAt(rowIndex, AbstractVcsLogTableModel.COMMIT_COLUMN);
   if (commitValue instanceof GraphCommitCell) {
     GraphCommitCell commitCell = (GraphCommitCell) commitValue;
     return commitCell.getPrintCell();
   }
   return null;
 }
 /**
  * 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());
 }
  @Override
  public void updateValues() {
    List<KeyValueProperty> items = new LinkedList<>();
    TableModel model = itemsTable.getModel();
    int size = model.getRowCount();

    for (int i = 0; i < size; i++) {
      String key = (String) model.getValueAt(i, 0);
      String value = (String) model.getValueAt(i, 1);
      items.add(new KeyValueProperty(null, key, value));
    }

    fProperty.setItems(items);
  }
Ejemplo n.º 15
0
  private Row[] getViewToModel() {
    if (viewToModel == null) {
      int tableModelRowCount = tableModel.getRowCount();
      viewToModel = new Row[tableModelRowCount];
      for (int row = 0; row < tableModelRowCount; row++) {
        viewToModel[row] = new Row(row);
      }

      if (isSorting()) {
        Arrays.sort(viewToModel);
      }
    }
    return viewToModel;
  }
  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;
  }
Ejemplo n.º 17
0
  public static boolean someCheckBoxIsTicked(JTable table, int column) {
    TableModel model = table.getModel();
    int rowCount = model.getRowCount();

    for (int row = 0; row < rowCount; row++) {
      boolean ticked = Boolean.parseBoolean(String.valueOf(model.getValueAt(row, column)));

      if (ticked) {
        return true;
      }
    }

    return false;
  }
Ejemplo n.º 18
0
  public static int countTickedCheckBox(JTable table, int column) {
    TableModel model = table.getModel();
    int rowCount = model.getRowCount();
    int count = 0;

    for (int row = 0; row < rowCount; row++) {
      boolean ticked = Boolean.parseBoolean(String.valueOf(model.getValueAt(row, column)));

      if (ticked) {
        count++;
      }
    }

    return count;
  }
Ejemplo n.º 19
0
    @Override
    public boolean stopCellEditing() {
      JTextField field = (JTextField) getComponent();
      String text = field.getText();
      boolean validCell = true;
      TableModel model = sourceRoots.getModel();
      int rowCount = model.getRowCount();
      for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
        String value = (String) model.getValueAt(rowIndex, 1);
        if (text.equals(value)) {
          validCell = false;
        }
      }
      model = testRoots.getModel();
      rowCount = model.getRowCount();
      for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
        String value = (String) model.getValueAt(rowIndex, 1);
        if (text.equals(value)) {
          validCell = false;
        }
      }

      return validCell == false ? validCell : super.stopCellEditing();
    }
Ejemplo n.º 20
0
 /**
  * Display the tree rooted at node tn in the graph as a dendogram.
  *
  * @param tn the root node of the tree to display
  */
 private void display(TreeNode tn) {
   double[] segs = dendogram(tn);
   double distance = 10.;
   if (tn instanceof Cluster) {
     distance = ((Cluster) tn).getSimilarity();
   } else {
     distance = ((DefaultMutableTreeNode) tn).getDepth();
   }
   gs.setData(segs, GraphDataModel.FORMAT_XY);
   graph.getXAxis().setMin(distance);
   graph.getXAxis().setMax(0.);
   graph.getYAxis().setMin(tm.getRowCount() - .5);
   graph.getYAxis().setMax(-.5);
   repaint();
 }
 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;
 }
  public void actionPerformed(ActionEvent e) {
    try {
      TableModel model = graph.getModel();
      if (model.getRowCount() == 0) {
        UISupport.showErrorMessage("No data to export!");
        return;
      }

      File file = UISupport.getFileDialogs().saveAs(this, "Select file for export");
      if (file == null) return;

      int cnt = exportToFile(file, model);

      UISupport.showInfoMessage("Saved " + cnt + " rows to file [" + file.getName() + "]");
    } catch (IOException e1) {
      SoapUI.logError(e1);
    }
  }
  /** 导出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) {
    }
  }
Ejemplo n.º 24
0
 void generateReport(final ReportGenerator rGen) {
   rGen.setTemplate(properties.getProperty("Template File"));
   rGen.setProperties(properties);
   final Collection<TableColumnModel> columnModels = new ArrayList<TableColumnModel>();
   for (JTable table : tables) {
     columnModels.add(table.getColumnModel());
   }
   rGen.setTableData(
       jpc.getModel(), jpc.getUberSelection(), TableUtils.combineColumnModels(columnModels));
   final TableModel imageTableModel = imageTable.getModel();
   final List<JComponent> comps = new ArrayList<JComponent>();
   for (int row = 0; row < imageTableModel.getRowCount(); row++) {
     if (imageTableModel.getValueAt(row, 3) == Boolean.TRUE) {
       comps.add((JComponent) imageTableModel.getValueAt(row, 0));
     }
   }
   rGen.setComponentsToAppend(comps);
   rGen.populateTemplate();
 }
Ejemplo n.º 25
0
  /**
   * Calculates the optimal width for the column of the given table. The calculation is based on the
   * preferred width of the header and cell renderer. <br>
   * Taken from the newsgoup de.comp.lang.java with some modifications.<br>
   * Taken from FOPPS/EnhancedTable - http://fopps.sourceforge.net/<br>
   *
   * @param table the table to calculate the column width
   * @param col the column to calculate the widths
   * @return the width, -1 if error
   */
  public static int calcColumnWidth(JTable table, int col) {
    int width = calcHeaderWidth(table, col);
    if (width == -1) return width;

    TableColumnModel columns = table.getColumnModel();
    TableModel data = table.getModel();
    int rowCount = data.getRowCount();
    TableColumn column = columns.getColumn(col);
    try {
      for (int row = rowCount - 1; row >= 0; --row) {
        Component c = table.prepareRenderer(table.getCellRenderer(row, col), row, col);
        width = Math.max(width, c.getPreferredSize().width + 10);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return width;
  }
  /**
   * Gets all GUI automations
   *
   * @return An array with all GUI automations
   */
  public GUIAutomation[] getGUIAutomations() {

    TableModel model = configurationTable.getModel();
    int numberOfConfigurations = model.getRowCount();
    GUIAutomation[] guiAutomations = new GUIAutomation[numberOfConfigurations];

    // stop open edits
    if (configurationTable.isEditing()) {
      configurationTable.getCellEditor().stopCellEditing();
    }

    // build GUI automation objects
    for (int i = 0; i < numberOfConfigurations; i++) {

      ScaleableImageIcon image =
          (ScaleableImageIcon) model.getValueAt(i, ConfigurationTableModel.COLUMN_INDEX_IMAGE);

      // check for valid image
      String imagePath = null;
      if (image != null) {
        imagePath = image.getPath();
      }

      String type = (String) model.getValueAt(i, ConfigurationTableModel.COLUMN_INDEX_TYPE);
      String trigger = (String) model.getValueAt(i, ConfigurationTableModel.COLUMN_INDEX_TRIGGER);
      String midiSignature =
          (String) model.getValueAt(i, ConfigurationTableModel.COLUMN_INDEX_MIDI_SIGNATURE);
      long delay = (long) model.getValueAt(i, ConfigurationTableModel.COLUMN_INDEX_MIN_DELAY);
      float minSimilarity =
          (float) model.getValueAt(i, ConfigurationTableModel.COLUMN_INDEX_MIN_SIMILARITY);
      boolean isMovable =
          (boolean) model.getValueAt(i, ConfigurationTableModel.COLUMN_INDEX_MOVABLE);

      GUIAutomation guiAutomation =
          new GUIAutomation(
              imagePath, type, trigger, delay, midiSignature, minSimilarity, isMovable);
      guiAutomations[i] = guiAutomation;
    }

    return guiAutomations;
  }
  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);
    }
  }
Ejemplo n.º 28
0
 /**
  * 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;
 }
Ejemplo n.º 29
0
  /**
   * This method picks good column sizes. If all column heads are wider than the column's cells'
   * contents, then you can just use column.sizeWidthToFit().
   */
  private void initColumnSizes(JTable table) {
    TableModel model = table.getModel();
    if (model.getRowCount() > 0) {
      TableColumn column = null;
      Component comp = null;
      int cellWidth = 0;
      TableColumnModel columnModel = table.getColumnModel();

      for (int i = 0; i < columnModel.getColumnCount(); i++) {
        column = columnModel.getColumn(i);

        for (int j = 0; j < table.getRowCount(); j++) {
          TableCellRenderer cellRenderer = table.getCellRenderer(j, i);
          comp =
              cellRenderer.getTableCellRendererComponent(
                  table, model.getValueAt(j, i), false, false, j, i);
          cellWidth = comp.getPreferredSize().width;
          column.setPreferredWidth(Math.max(column.getPreferredWidth(), cellWidth));
        }
      }
    }
  }
Ejemplo n.º 30
0
  public void calculaSumas() {
    try {
      TableModel tm = this.tablaPrincipal.getModel();
      int tamTabla = tm.getRowCount();
      double costo, cantidad, totalFila, sumaTotal;
      sumaTotal = 0.0;

      for (int i = 0; i < tamTabla; i++) {
        if (tm.getValueAt(i, 2) != null && tm.getValueAt(i, 3) != null) {
          costo = Double.valueOf(String.valueOf(tm.getValueAt(i, 2)));
          cantidad = Double.valueOf(String.valueOf(tm.getValueAt(i, 3)));
          totalFila = costo * cantidad;

          tm.setValueAt(totalFila, i, 4);
          sumaTotal += totalFila;
        }
      }

      txtSumaTotal.setText(String.valueOf(sumaTotal));
    } catch (Exception e) {
      Dialogos.lanzarAlerta("Cantidades invalidas, puede que algun numero este mal escrito");
    }
  }