Exemple #1
2
  public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand().equals(PUT)) {
      while (availableExpressions.getSelectedIndex() != -1) {
        String exp = (String) availableExpressions.getSelectedValue();
        setAsSelected(exp, true);
      }
    } else if (ae.getActionCommand().equals(PUSH)) {
      while (selectedExpressions.getSelectedRow() != -1) {
        String exp =
            (String) selectedExpressions.getValueAt(selectedExpressions.getSelectedRow(), 1);
        ((DefaultTableModel) selectedExpressions.getModel())
            .removeRow(selectedExpressions.getSelectedRow());
        ((DefaultListModel) availableExpressions.getModel()).addElement(exp);
      }
    } else if (ae.getActionCommand().equals(UP)) {
      int row = selectedExpressions.getSelectedRow();
      if (row < 1) return;
      ((DefaultTableModel) selectedExpressions.getModel()).moveRow(row, row, --row);
      selectedExpressions.setRowSelectionInterval(row, row);
      scrollToRow(row);
    } else if (ae.getActionCommand().equals(DOWN)) {
      int row = selectedExpressions.getSelectedRow();
      if (row == selectedExpressions.getRowCount() - 1) return;
      ((DefaultTableModel) selectedExpressions.getModel()).moveRow(row, row, ++row);
      selectedExpressions.setRowSelectionInterval(row, row);
      scrollToRow(row);
    }

    clauses.builder.syntax.refresh();
  }
  private void obtenerPrecio(java.math.BigDecimal valorRetorno) {

    java.math.BigDecimal parcial =
        new java.math.BigDecimal(valorRetorno == null ? "0.00" : valorRetorno.toString().trim());

    java.math.BigDecimal cantidad =
        new java.math.BigDecimal(
            tabla.getValueAt(fila, buscarColumna("Cantidad", tabla)).toString().trim().isEmpty()
                ? "1.00"
                : tabla.getValueAt(fila, buscarColumna("Cantidad", tabla)).toString().trim());

    java.math.BigDecimal precio = parcial.divide(cantidad, 15, java.math.RoundingMode.HALF_EVEN);

    java.math.BigDecimal porcentaje =
        new java.math.BigDecimal(
            tabla.getValueAt(fila, buscarColumna("%", tabla)).toString().trim().isEmpty()
                ? "1.00"
                : tabla.getValueAt(fila, buscarColumna("%", tabla)).toString().trim());

    java.math.BigDecimal valorPorcentaje =
        parcial.multiply(porcentaje).divide(new java.math.BigDecimal("100.00"));
    java.math.BigDecimal valorsubTotal = parcial.subtract(valorPorcentaje);

    tabla.setValueAt(precio, fila, buscarColumna("Precio", tabla));

    tabla.setValueAt(valorPorcentaje, fila, buscarColumna("Descuento", tabla));

    tabla.setValueAt(valorsubTotal, fila, buscarColumna("Subtotal", tabla));
    tabla.updateUI();
  }
Exemple #3
0
  // 监听到行号,将所选行的内容依次赋到 schedule对象,以便传有值对象到修改面板进行修改
  public void mouseClicked(MouseEvent event) {
    int row = jt.getSelectedRow();
    schedule.setSched_id(Integer.parseInt(jt.getValueAt(row, 0).toString()));
    schedule.setStudio_id(
        new StudioSrv()
            .Fetch("studio_name = '" + jt.getValueAt(row, 1).toString() + "'")
            .get(0)
            .getId());
    schedule.setPlay_id(
        new PlaySrv()
            .Fetch("play_name = '" + jt.getValueAt(row, 2).toString() + "'")
            .get(0)
            .getId()); // 0
    java.text.SimpleDateFormat sdf =
        new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 小写的mm表示的是分钟
    java.util.Date date = null;
    try {

      date = sdf.parse(jt.getValueAt(row, 3).toString());
      //	date = new Timestamp(jt.getValueAt(row, 3).toString());
    } catch (ParseException e) {
      e.printStackTrace();
    }
    schedule.setSched_time(date);
    schedule.setSched_ticket_price(Float.parseFloat(jt.getValueAt(row, 4).toString())); // 0
  }
  @Override
  public IEntity save() {
    if (idDepartment == 0) {
      return null;
    }
    float sumMoneyImport = Float.parseFloat(tableSB32.getValueAt(0, 1).toString().trim());
    float sumMoneyExport = Float.parseFloat(tableSB32.getValueAt(0, 3).toString().trim());
    float sumProfit = Float.parseFloat(tableSB32.getValueAt(1, 1).toString().trim());
    String proportionProfit = tableSB32.getValueAt(1, 3).toString().trim();
    String estimate = tableSB32.getValueAt(2, 1).toString().trim();

    DepartmentExt_W43 bean = dao.getByObjectId(String.valueOf(idDepartment));
    if (bean == null) {
      bean = new DepartmentExt_W43();
    }
    bean.setDepartmentIdActual(idDepartment);
    bean.setSumMoneyImport(sumMoneyImport);
    bean.setSumMoneyExport(sumMoneyExport);
    bean.setSumprofit(sumProfit);
    bean.setProportionProfit(proportionProfit);
    bean.setEstimate(estimate);

    dao.update(bean);
    reset();

    return bean;
  }
  private void obtenerValorPorcentaje(java.math.BigDecimal valorPorcentaje) {

    java.math.BigDecimal porcentaje =
        new java.math.BigDecimal(
            valorPorcentaje == null ? "0.00" : valorPorcentaje.toString().trim());

    java.math.BigDecimal parcial =
        new java.math.BigDecimal(
            tabla.getValueAt(fila, buscarColumna("Parcial", tabla)).toString().trim().isEmpty()
                ? "1.00"
                : tabla.getValueAt(fila, buscarColumna("Parcial", tabla)).toString().trim());

    java.math.BigDecimal porcentajeFinal =
        (porcentaje
            .multiply(parcial)
            .divide(new java.math.BigDecimal("100.00"), 15, java.math.RoundingMode.HALF_EVEN));

    /// PARA PONER EL VALOR DECIMAL EN EL CAMPO PRECIO
    tabla.setValueAt(porcentajeFinal, fila, buscarColumna("Descuento", tabla));

    /// PARA PONER EL VALOR EN SUBTOTAL
    tabla.setValueAt(parcial.subtract(porcentajeFinal), fila, buscarColumna("Subtotal", tabla));

    //        ///PARA PONER EL VALOR ENTERO EN EL CAMPO CANTIDAD
    //        tabla.setValueAt(cantidad.toString().substring(0, cantidad.toString().indexOf(".")),
    //                fila, buscarColumna("Cantidad", tabla));
    tabla.updateUI();
  }
 @Override
 public void mouseClicked(MouseEvent e) {
   JTable table = (JTable) e.getSource();
   Point point = e.getPoint();
   int clickedRow = table.rowAtPoint(point);
   int clickedCol = table.columnAtPoint(point);
   if ((clickedCol == -1) || (clickedRow == -1)) {
     return;
   }
   if (table.getValueAt(clickedRow, clickedCol) instanceof StringUrl) {
     // retrieve the link to go to
     String sUrl = ((StringUrl) table.getValueAt(clickedRow, clickedCol)).getUrl();
     URL url;
     try {
       url = new URL(sUrl);
       log.debug("showing url for " + url);
       HtmlBrowser.URLDisplayer.getDefault().showURL(url);
       // prevent this from getting called again as it works it's way up the component stack
       e.consume();
     } catch (MalformedURLException ex) {
       StatusBar.getInstance()
           .setStatusText("\"" + sUrl + "\" is not a valid URL. Cannot open in browser.");
       log.warn(
           "\""
               + sUrl
               + "\" is not a valid URL. Cannot open in browser.\n\n"
               + ex.getLocalizedMessage());
     }
   }
 }
  // Implementation of valueChanged
  public void valueChanged(ListSelectionEvent e) {
    if (e.getSource() == table.getSelectionModel()) {
      ListSelectionModel ls = table.getSelectionModel();

      int index = ls.getMinSelectionIndex();
      long id = (long) table.getValueAt(index, 0);

      updateFeesData(id);
    } else {
      ListSelectionModel ls = feestable.getSelectionModel();

      int index = ls.getMinSelectionIndex();

      float feespayed = (float) feestable.getValueAt(index, 1);
      float totalfees = (float) feestable.getValueAt(index, 2);

      feespayedlabel.setText("Fees Payed: " + feespayed);
      totalfeeslabel.setText("Total Fees: " + totalfees);

      if (totalfees - feespayed > 0) {
        feesduelabel.setText("Fees Due: " + (totalfees - feespayed));
      }

      panel_6.revalidate();
    }
  }
  @Override
  public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    // based on columns in SystemTimeTableModel
    if (column == 0) {
      setHorizontalAlignment(SwingConstants.TRAILING);
    } else if (column == 1) {
      long start = (Long) value;
      long intervalStart = toCompare.getStart();

      if (start == intervalStart) {
        setFont(Styles.BOLD_ITALIC);
      } else if (intervalStart < start) {
        if (toCompare.getEnd() < start) {
          setFont(Styles.STRIKETHROUGH);
        } else {
          setFont(Styles.BOLD);
        }
      } else {
        long end = (Long) table.getValueAt(row, column + 1);

        if (intervalStart > end) {
          setFont(Styles.STRIKETHROUGH);
        }
        // else leave unformatted
      }

      setText(TimeFormatCache.formatDateTime(start));
    } else if (column == 2) {
      long end = (Long) value;
      long intervalEnd = toCompare.getEnd();

      if (end == intervalEnd) {
        setFont(Styles.BOLD_ITALIC);
      } else if (intervalEnd > end) {
        if (toCompare.getStart() > end) {
          setFont(Styles.STRIKETHROUGH);
        } else {
          setFont(Styles.BOLD);
        }
      } else {
        long start = (Long) table.getValueAt(row, column - 1);

        if (intervalEnd < start) {
          setFont(Styles.STRIKETHROUGH);
        }
        // else leave unformatted
      }

      setText(TimeFormatCache.formatDateTime(end));
    } else if (column == 3) {
      setHorizontalAlignment(SwingConstants.CENTER);
    }
    // else just return the value

    return this;
  }
 private void btnMessageWaehlenClicked() {
   int selectedRow[] = _tblMessages.getSelectedRows();
   if (selectedRow.length != 0) {
     String title = (String) _tblMessages.getValueAt(selectedRow[0], 0);
     String message = (String) _tblMessages.getValueAt(selectedRow[0], 1);
     _ctrl.selectedMessage(new DTOMessage(title, message, null, ""));
   }
 }
  private void SetProduto() {
    int linha = table.getSelectedRow();

    this.produto.setId_produto(Integer.parseInt(table.getValueAt(linha, 0).toString()));
    this.produto.setDescricao(table.getValueAt(linha, 1).toString());
    this.produto.setEstoque(Float.valueOf(table.getValueAt(linha, 2).toString()));
    this.produto.setPr_venda(Float.valueOf(table.getValueAt(linha, 3).toString()));
  }
Exemple #11
0
  /**
   * Runs search within table
   *
   * @return Returns true if found
   */
  private boolean runSearch() {

    ListSelectionModel lsm = table.getSelectionModel();
    foundRowIndices = new Vector();
    boolean selectAll = this.selectAllButton.isSelected();
    boolean found = false;

    searchStr = (String) this.jComboBox1.getSelectedItem();
    if (searchStr == null || numSearchCols == 0 || searchStr.equals("")) return found;

    table.clearSelection();
    this.jComboBox1.insertItemAt(searchStr, 0);

    if (this.matchCaseChkBox.isSelected()) {
      for (int row = 0; row < numRows; row++) {

        for (int col = (numClasses + 2); col < numCols; col++) {
          if (((String) table.getValueAt(row, col)).indexOf(searchStr) != -1) {
            // select row;
            if (selectAll || !found) {
              table.addRowSelectionInterval(row, row);
              // first occurance
              if (!found) {
                table.scrollRectToVisible(table.getCellRect(row, 0, true));
                found = true;
              }
            } else foundRowIndices.add(new Integer(row));
            break;
          }
        }
      }
    } else {

      String upperCaseStr = searchStr.toUpperCase();

      for (int row = 0; row < numRows; row++) {

        for (int col = (numClasses + 2); col < numCols; col++) {
          if ((((String) table.getValueAt(row, col)).toUpperCase()).indexOf(upperCaseStr) != -1) {
            // select row;
            if (selectAll || !found) {
              table.addRowSelectionInterval(row, row);
              // first occurance
              if (!found) {
                table.scrollRectToVisible(table.getCellRect(row, 0, true));
                found = true;
              }
            } else foundRowIndices.add(new Integer(row));
            break;
          }
        }
      }
    }

    return found;
  }
Exemple #12
0
  @Override
  public void tableChanged(TableModelEvent tME) {
    if (tME.getType() == TableModelEvent.UPDATE && tME.getSource().equals(sitesTableModel)) {
      try {
        Statement MySQL_Statement = dbConn.createStatement();
        String updSourceSQL =
            "UPDATE sites SET given_name="
                + (sitesTable.getValueAt(tME.getFirstRow(), 1).toString().equals("")
                    ? "NULL"
                    : "'" + sitesTable.getValueAt(tME.getFirstRow(), 1).toString() + "'")
                + ",surname="
                + (sitesTable.getValueAt(tME.getFirstRow(), 2).toString().equals("")
                    ? "NULL"
                    : "'" + sitesTable.getValueAt(tME.getFirstRow(), 2).toString() + "'")
                + ",suburb="
                + (sitesTable.getValueAt(tME.getFirstRow(), 3).toString().equals("")
                    ? "NULL"
                    : "'" + sitesTable.getValueAt(tME.getFirstRow(), 3).toString() + "'")
                + ",state="
                + (sitesTable.getValueAt(tME.getFirstRow(), 4).toString().equals("")
                    ? "NULL"
                    : "'" + sitesTable.getValueAt(tME.getFirstRow(), 4).toString() + "'")
                + " WHERE site_id = "
                + sitesTable
                    .getValueAt(tME.getFirstRow(), 0)
                    .toString(); // updates specified information into the database
        System.out.println(updSourceSQL);
        MySQL_Statement.executeUpdate(updSourceSQL);

      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
  private void obtenerValorPorcentaje(java.math.BigDecimal valorDescuento) {

    try {
      //////////////////////////// ESTO ES PARA OBTENER EL PORCENTAJE
      java.math.BigDecimal parcial =
          new java.math.BigDecimal(
              tabla.getValueAt(fila, buscarColumna("Parcial", tabla)) == null
                      || tabla
                          .getValueAt(fila, buscarColumna("Parcial", tabla))
                          .toString()
                          .trim()
                          .isEmpty()
                  ? "0.00"
                  : tabla.getValueAt(fila, buscarColumna("Parcial", tabla)).toString().trim());

      java.math.BigDecimal descuento =
          new java.math.BigDecimal(
              valorDescuento == null ? "0.00" : valorDescuento.toString().trim());

      java.math.BigDecimal multiplicacion = descuento.multiply(new java.math.BigDecimal("100.00"));
      java.math.BigDecimal division = cero;

      if (parcial.compareTo(cero) > 0)
        division = multiplicacion.divide(parcial, 15, java.math.RoundingMode.HALF_UP);
      tabla.setValueAt(division.toPlainString(), fila, buscarColumna("%", tabla));

      /// PARA PONER EL SUBTOTAL
      //            table.setValueAt(parcial.subtract(division), fila, buscarColumna("Subtotal"));
      //            if (division.compareTo(mDIShrimp.getCero()) == 0){
      //                table.setValueAt(parcial.subtract(division), fila,
      // buscarColumna("Subtotal"));
      //            } else {
      //                table.setValueAt(division.subtract(parcial), fila,
      // buscarColumna("Subtotal"));
      //            }

      tabla.repaint();
    } catch (Exception e) {
      shrimp.helper.JDVentanaMensajes.showMessageDialog(
          new javax.swing.JFrame(),
          "Ha ocurrido un error inesperado en el formulario",
          javax.swing.JOptionPane.ERROR_MESSAGE,
          javax.swing.JOptionPane.DEFAULT_OPTION,
          e,
          null);
    }

    //        ///PARA PONER EL VALOR ENTERO EN EL CAMPO CANTIDAD
    //        tabla.setValueAt(cantidad.toString().substring(0, cantidad.toString().indexOf(".")),
    //                fila, buscarColumna("Cantidad", tabla));
    tabla.updateUI();
  }
Exemple #14
0
 private void actualizarPrecio() {
   BigDecimal importe;
   BigDecimal total = new BigDecimal(0);
   for (int i = 0; i < tablafac.getRowCount(); i++) {
     importe =
         BigDecimal.valueOf((Integer) tablafac.getValueAt(i, 1))
             .multiply((BigDecimal) ventaGui.getTablaFactura().getValueAt(i, 3));
     tablafac.setValueAt(importe, i, 4);
   }
   for (int i = 0; i < tablafac.getRowCount(); i++) {
     total = total.add((BigDecimal) tablafac.getValueAt(i, 4));
   }
   ventaGui.getTotalFactura().setText(total.toString());
 }
    @Override
    public void mouseClicked(MouseEvent e) {
      int columna = jTable.getColumnModel().getColumnIndexAtX(e.getX());
      int fila = e.getY() / jTable.getRowHeight();

      if ((fila < jTable.getRowCount() && fila >= 0)
          && (columna < jTable.getColumnCount() && columna >= 0)) {

        if (jTable.getValueAt(fila, columna) instanceof JButton) {
          JButton btn = (JButton) jTable.getValueAt(fila, columna);
          btn.doClick();
        }
      }
    }
  public TPedido obtenerPedido() {

    TPedido tpedido = new TPedido();

    JTable tbpedidos = getTbPedidos();
    int fila_sel = tbpedidos.getSelectedRow();

    tpedido.setId_pedido((int) tbpedidos.getValueAt(fila_sel, 0));
    tpedido.setId_proveedor((int) tbpedidos.getValueAt(fila_sel, 1));
    tpedido.setFechaRealizado((String) tbpedidos.getValueAt(fila_sel, 2));
    tpedido.setFechaEntregado((String) tbpedidos.getValueAt(fila_sel, 3));
    tpedido.setFechaCancelado((String) tbpedidos.getValueAt(fila_sel, 4));

    JTable tbproductos = getTbProductos();

    int filas = tbproductos.getRowCount();

    List<TProductoDePedido> listaproductos = new ArrayList<TProductoDePedido>();
    for (int i = 0; i < filas; i++) // recorre toda la tabla productos del pedido fila a fila
    {
      TProductoDePedido tproducto = new TProductoDePedido();
      tproducto.setProducto((int) tbproductos.getValueAt(i, 0));
      tproducto.setPedido((int) tbpedidos.getValueAt(fila_sel, 0));
      tproducto.setPrecio((double) tbproductos.getValueAt(i, 1));
      tproducto.setCantidad((int) tbproductos.getValueAt(i, 2));

      listaproductos.add(tproducto);
    }

    tpedido.setListaProductosPedido(listaproductos);

    return tpedido;
  }
  public void calculate_total() {

    String text = "Total :-       ";
    int tbl_row_count = tbl_service_details.getRowCount();
    double total = 0;

    for (int i = 0; i < tbl_row_count; i++) {
      if (tbl_service_details.getValueAt(i, 7) != null)
        total = total + (double) tbl_service_details.getValueAt(i, 7);
    }

    text = text + total + "  ";
    lbl_total.setText(text);
  }
  @Test
  public void variablesProperty() {
    final JTable table = new JTable();
    bindingContext.bind("conditions", new ConditionsTableAdapter(table));
    assertTrue(table.getModel() instanceof DefaultTableModel);

    final DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
    tableModel.addRow((Object[]) null);
    tableModel.addRow((Object[]) null);

    assertEquals(2, table.getRowCount());

    table.setValueAt("a", 0, 0);
    assertEquals("a", table.getValueAt(0, 0));
    table.setValueAt("A", 0, 1);
    assertEquals("A", table.getValueAt(0, 1));
    table.setValueAt(true, 0, 2);
    assertEquals(true, table.getValueAt(0, 2));

    table.setValueAt("b", 1, 0);
    assertEquals("b", table.getValueAt(1, 0));
    table.setValueAt("B", 1, 1);
    assertEquals("B", table.getValueAt(1, 1));
    table.setValueAt(false, 1, 2);
    assertEquals(false, table.getValueAt(1, 2));

    bindingContext
        .getPropertySet()
        .setValue("conditions", new MosaicOp.Condition[] {new MosaicOp.Condition("d", "D", true)});

    assertEquals(1, table.getRowCount());
    assertEquals("d", table.getValueAt(0, 0));
    assertEquals("D", table.getValueAt(0, 1));
    assertEquals(true, table.getValueAt(0, 2));
  }
  public void actualizarDatos(JTable tabla) {
    double validacion = 0.0;
    int cantidadFilas = tabla.getRowCount();
    int contador = 0;
    boolean boleano = true;
    HashSet<Date> validadorFechas = new HashSet<Date>();

    try {
      // Validacion acuerdo
      while (contador != cantidadFilas) {
        validadorFechas.add(formatoFecha.parse(String.valueOf(tabla.getValueAt(contador, 3))));
        validacion = validacion + Double.parseDouble(String.valueOf(tabla.getValueAt(contador, 4)));
        contador++;
      }
      if (validadorFechas.size() != cantidadFilas) {
        JOptionPane.showMessageDialog(
            this,
            "Hay fechas identicas, los acuerdos no pueden tener una misma fecha de pago. ",
            "DENEGADO",
            JOptionPane.ERROR_MESSAGE);
        boleano = false;
      }
      if (boleano == true) {
        int respuesta =
            JOptionPane.showConfirmDialog(
                this,
                "¿Está seguro que desea guardar los cambios?",
                "CONFIRMACION",
                JOptionPane.YES_NO_OPTION);
        if (respuesta == JOptionPane.YES_OPTION) {
          if (Conexion.getInstancia().datosAcuerdo(idDeuda, validacion, tabla, false) == true) {
            JOptionPane.showMessageDialog(
                this,
                "Se ha modificado el acuerdo correctamente.",
                "COMPLETADO",
                JOptionPane.INFORMATION_MESSAGE);
            Conexion.getInstancia().consultaAcuerdo(MantenimientoDeAcuerdo.getTablaAcuerdo());
            dispose();
          } else {
            validacion = 0;
          }
        }
      }
    } catch (SQLException e1) {
      e1.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
    /**
     * Get the properties being edited
     *
     * @return the map of properties being edited
     */
    public Map<String, String> getProperties() {
      Map<String, String> result = new HashMap<String, String>();
      JTable table = m_table.getTable();
      int numRows = table.getModel().getRowCount();

      for (int i = 0; i < numRows; i++) {
        String paramName = table.getValueAt(i, 0).toString();
        String paramValue = table.getValueAt(i, 1).toString();
        if (paramName.length() > 0 && paramValue.length() > 0) {
          result.put(paramName, paramValue);
        }
      }

      return result;
    }
 // call the ontology printer and update the textPane
 @Override
 public synchronized void mouseReleased(MouseEvent arg0) {
   // TODO Auto-generated method stub
   int selectionRow = table.getSelectedRow();
   int selectionCol = table.getSelectedColumn();
   if (selectionRow != -1 && selectionCol == 2) {
     OFDebugLogger tmp = OFDebugLogger.getAllInstances().get(table.getValueAt(selectionRow, 1));
     Boolean boo = (Boolean) table.getValueAt(selectionRow, selectionCol);
     table.setValueAt(!boo, selectionRow, selectionCol);
     tmp.setFlagToFollow(!boo); // .setFlagToFollow( !boo, this);
     update();
     model.fireTableDataChanged();
   }
   table.repaint();
 }
 /**
  * auto fit table columns width
  *
  * @version 1.0
  * @author dinglinhui
  */
 public void FitTableColumns(JTable myTable) {
   JTableHeader header = myTable.getTableHeader();
   int rowCount = myTable.getRowCount();
   Enumeration columns = myTable.getColumnModel().getColumns();
   while (columns.hasMoreElements()) {
     TableColumn column = (TableColumn) columns.nextElement();
     int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
     int width =
         (int)
             myTable
                 .getTableHeader()
                 .getDefaultRenderer()
                 .getTableCellRendererComponent(
                     myTable, column.getIdentifier(), false, false, -1, col)
                 .getPreferredSize()
                 .getWidth();
     for (int row = 0; row < rowCount; row++) {
       int preferedWidth =
           (int)
               myTable
                   .getCellRenderer(row, col)
                   .getTableCellRendererComponent(
                       myTable, myTable.getValueAt(row, col), false, false, row, col)
                   .getPreferredSize()
                   .getWidth();
       width = Math.max(width, preferedWidth);
     }
     header.setResizingColumn(column); // 此行很重要
     column.setWidth(width + myTable.getIntercellSpacing().width);
   }
 }
  private static int preferredWidth(JTable table, int col) {
    TableColumn tableColumn = table.getColumnModel().getColumn(col);
    int width =
        (int)
            table
                .getTableHeader()
                .getDefaultRenderer()
                .getTableCellRendererComponent(
                    table, tableColumn.getIdentifier(), false, false, -1, col)
                .getPreferredSize()
                .getWidth();

    if (table.getRowCount() != 0) {
      int from = 0, to = 0;
      Rectangle rect = table.getVisibleRect();
      from = table.rowAtPoint(rect.getLocation());
      to = table.rowAtPoint(new Point((int) rect.getMaxX(), (int) rect.getMaxY())) + 1;

      for (int row = from; row < to; row++) {
        int preferedWidth =
            (int)
                table
                    .getCellRenderer(row, col)
                    .getTableCellRendererComponent(
                        table, table.getValueAt(row, col), false, false, row, col)
                    .getPreferredSize()
                    .getWidth();
        width = Math.max(width, preferedWidth);
      }
    }
    return width + table.getIntercellSpacing().width;
  }
  private void modificarPersona() {
    try {
      int dialogButton = JOptionPane.YES_NO_OPTION;
      int dialogResult =
          JOptionPane.showConfirmDialog(
              this,
              "¿Esta seguro que desea eliminar el cliente...?",
              "Eliminar Cliente",
              dialogButton);
      if (dialogResult == 0) {
        int dniPersona =
            Integer.parseInt(tblPersonas.getValueAt(tblPersonas.getSelectedRow(), 0).toString());
        personas.setDnipersona(dniPersona);
        personas.setApellido(txtApellido.getText());
        personas.setNombre(txtNombre.getText());
        personas.setDireccion(txtDireccion.getText());
        personas.setTelefono(txtTelefono.getText());
        personas.setEmail(txtEmail.getText());
        personas.setCuil(txtCuil.getText());
        Date fechaHoy = new Date();
        personas.setFechaalta(fechaHoy);
        personas.setPerfil(cmbPerfil.getSelectedItem().toString());
        impPersonas.update(personas);
      } else {

      }
    } catch (ArrayIndexOutOfBoundsException e) {
      JOptionPane.showMessageDialog(rootPane, "Primero seleccione el Cliente a eliminar!!!");
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(rootPane, "Error");
    } catch (org.hibernate.exception.ConstraintViolationException e) {
      JOptionPane.showMessageDialog(
          rootPane, "Debe imprimir los Codigos de Barras para poder eliminar...");
    }
  }
  private void eliminarPersona() {
    try {
      int dialogButton = JOptionPane.YES_NO_OPTION;
      int dialogResult =
          JOptionPane.showConfirmDialog(
              this,
              "¿Esta seguro que desea eliminar el cliente...?",
              "Eliminar Cliente",
              dialogButton);
      if (dialogResult == 0) {
        int dniPersona =
            Integer.parseInt(tblPersonas.getValueAt(tblPersonas.getSelectedRow(), 0).toString());
        personas.setDnipersona(dniPersona);
        impPersonas.delete(personas);
      } else {

      }
    } catch (ArrayIndexOutOfBoundsException e) {
      JOptionPane.showMessageDialog(rootPane, "Primero seleccione el Cliente a eliminar!!!");
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(rootPane, "Error");
    } catch (org.hibernate.exception.ConstraintViolationException e) {
      JOptionPane.showMessageDialog(
          rootPane, "Debe imprimir los Codigos de Barras para poder eliminar...");
    }
  }
  private void packColumn(JTable table, int vColIndex, int margin) {
    //		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // obtiene la anchura de la cabecera de la columna
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
      renderer = table.getTableHeader().getDefaultRenderer();
    }
    Component comp =
        renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
    //		width = comp.getPreferredSize().width;
    width = 5;

    // Obtine la anchura maxima de la coluna de
    for (int r = 0; r < table.getRowCount(); r++) {
      renderer = table.getCellRenderer(r, vColIndex);
      comp =
          renderer.getTableCellRendererComponent(
              table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
      width = Math.max(width, 0);
    }

    width += 2 * margin;

    // Configura el ancho
    col.setPreferredWidth(width);
  }
Exemple #27
0
 private boolean existeProdFacc(int idProd) {
   boolean ret = false;
   for (int i = 0; i < tablafac.getRowCount() && !ret; i++) {
     ret = (Integer) tablafac.getValueAt(i, 0) == idProd;
   }
   return ret;
 }
 private static void drawSelection(JTable table, int column, Graphics g, final int width) {
   int y = 0;
   final int[] rows = table.getSelectedRows();
   final int height = table.getRowHeight();
   for (int row : rows) {
     final TableCellRenderer renderer = table.getCellRenderer(row, column);
     final Component component =
         renderer.getTableCellRendererComponent(
             table, table.getValueAt(row, column), false, false, row, column);
     g.translate(0, y);
     component.setBounds(0, 0, width, height);
     boolean wasOpaque = false;
     if (component instanceof JComponent) {
       final JComponent j = (JComponent) component;
       if (j.isOpaque()) wasOpaque = true;
       j.setOpaque(false);
     }
     component.paint(g);
     if (wasOpaque) {
       ((JComponent) component).setOpaque(true);
     }
     y += height;
     g.translate(0, -y);
   }
 }
Exemple #29
0
  public void packColumn(JTable table, int vColIndex, int margin) {
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // Get width of column header
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
      renderer = table.getTableHeader().getDefaultRenderer();
    }
    Component comp =
        renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
    width = comp.getPreferredSize().width;

    // Get maximum width of column data
    for (int r = 0; r < table.getRowCount(); r++) {
      renderer = table.getCellRenderer(r, vColIndex);
      comp =
          renderer.getTableCellRendererComponent(
              table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
      width = Math.max(width, comp.getPreferredSize().width);
    }

    // Add margin
    width += 2 * margin;

    // Set the width
    col.setPreferredWidth(width);
  }
  /**
   * Exports the given table to the given text file.
   *
   * @param fileName Name of the file
   * @param table Table to export
   * @throws IOException Thrown if an error occurs while writing to the file.
   */
  public void export(String fileName, JTable table) throws IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));

    // Export selected rows
    int[] rows = table.getSelectedRows();

    // Export entire table if there is no selection
    if (rows == null || rows.length < 1) {
      rows = new int[table.getRowCount()];
      for (int i = 0; i < rows.length; i++) {
        rows[i] = i;
      }
    }

    // Write headers
    for (int col = 0; col < table.getColumnCount(); col++) {
      bw.write(LINE_COMMENT);
      bw.write(table.getColumnName(col));
      if (col != table.getColumnCount()) bw.write(COL_DELIMITER);
    }
    bw.write(ROW_DELIMITER);

    // Write table content
    for (int row : rows) {
      for (int col = 0; col < table.getColumnCount(); col++) {
        Object o = table.getValueAt(row, col);
        if (o != null) bw.write(o.toString());
        if (col != table.getColumnCount()) bw.write(COL_DELIMITER);
      }
      bw.write(ROW_DELIMITER);
    }

    bw.close();
  }