Ejemplo n.º 1
0
  /**
   * 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;
  }
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();
    }
  }
  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();
  }
 /**
  * Retrieves the internationalized column name from the string array.
  *
  * @see TableModel#getColumnName(int)
  */
 public String getColumnName(final int columnIndex) {
   if (columnIndex < i18nKeys.length) {
     final String columnName = i18nKeys[columnIndex];
     if (columnName != null) {
       return columnName;
     }
   }
   return model.getColumnName(columnIndex);
 }
  @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();
      }
    }
  }
  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;
  }
Ejemplo n.º 8
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;
  }
  /** 导出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 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.º 11
0
 public String getColumnName(int column) {
   return model.getColumnName(column);
 }
Ejemplo n.º 12
0
  /**
   * 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;
  }
  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();
      }
    }
  }
  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 String getColumnName(int column) {
   return sourceModel.getColumnName(column);
 }
Ejemplo n.º 16
0
  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"));
    }
  }