Example usage for javax.swing.table DefaultTableModel getValueAt

List of usage examples for javax.swing.table DefaultTableModel getValueAt

Introduction

In this page you can find the example usage for javax.swing.table DefaultTableModel getValueAt.

Prototype

public Object getValueAt(int row, int column) 

Source Link

Document

Returns an attribute value for the cell at row and column.

Usage

From source file:library.Form_Library.java

License:asdf

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    JFileChooser chooser = new JFileChooser();
    int k = chooser.showSaveDialog(this);
    if (k == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {/*from   w w  w  .jav  a 2  s  .com*/
            FileWriter out = new FileWriter(file + ".xls");
            BufferedWriter bu = new BufferedWriter(out);
            DefaultTableModel model = (DefaultTableModel) tbBookAdmin.getModel();
            for (int i = 0; i < model.getColumnCount(); i++) {
                bu.write(model.getColumnName(i) + "\t");
            }
            bu.write("\n");
            for (int i = 0; i < model.getRowCount(); i++) {
                for (int j = 0; j < model.getColumnCount(); j++) {
                    bu.write(model.getValueAt(i, j) + "\t");
                }
                bu.write("\n");
            }
            bu.close();
            JOptionPane.showMessageDialog(this, "Saved");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Can't Save");
        }
    }
}

From source file:de.tor.tribes.ui.windows.TribeTribeAttackFrame.java

private void fireCalculateAttackEvent(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fireCalculateAttackEvent
    if (!jCalculateButton.isEnabled()) {
        logger.debug("Button disabled. Calculation is still running...");
        return;/*from  w w w .  ja v a  2s.c  o  m*/
    }
    //algorithm calculation
    //pre check
    DefaultTableModel victimModel = (DefaultTableModel) jVictimTable.getModel();
    DefaultTableModel attackModel = (DefaultTableModel) jSourcesTable.getModel();
    if (attackModel.getRowCount() == 0) {
        logger.warn("Validation of attacker tab failed");
        JOptionPaneHelper.showErrorBox(this, "Keine Herkunftsdrfer ausgewhlt", "Fehler");
        jideTabbedPane1.setSelectedIndex(0);
        return;
    }
    if (victimModel.getRowCount() == 0) {
        logger.warn("Validation of victim tab failed");
        JOptionPaneHelper.showErrorBox(this, "Keine Ziele ausgewhlt", "Fehler");
        jideTabbedPane1.setSelectedIndex(1);
        return;
    }
    if (!mSettingsPanel.validatePanel()) {
        logger.warn("Validation of settings tab failed");
        jideTabbedPane1.setSelectedIndex(2);
        return;
    }
    //reading values
    List<Village> victimVillages = new LinkedList<Village>();
    List<Village> victimVillagesFaked = new LinkedList<Village>();
    Hashtable<Village, Integer> maxAttacksTable = new Hashtable<Village, Integer>();
    for (int i = 0; i < victimModel.getRowCount(); i++) {
        if ((Boolean) victimModel.getValueAt(i, 2) == Boolean.TRUE) {
            victimVillagesFaked.add((Village) victimModel.getValueAt(i, 1));
        } else {
            victimVillages.add((Village) victimModel.getValueAt(i, 1));
        }
        maxAttacksTable.put((Village) victimModel.getValueAt(i, 1), (Integer) victimModel.getValueAt(i, 3));
    }
    //build source-unit map
    int snobSources = 0;
    // <editor-fold defaultstate="collapsed" desc=" Build attacks and fakes">
    Hashtable<UnitHolder, List<Village>> sources = new Hashtable<UnitHolder, List<Village>>();
    Hashtable<UnitHolder, List<Village>> fakes = new Hashtable<UnitHolder, List<Village>>();
    for (int i = 0; i < attackModel.getRowCount(); i++) {
        Village vSource = (Village) attackModel.getValueAt(i, 0);
        UnitHolder uSource = (UnitHolder) attackModel.getValueAt(i, 1);
        boolean fake = (Boolean) attackModel.getValueAt(i, 2);
        if (!fake) {
            List<Village> sourcesForUnit = sources.get(uSource);
            if (uSource.getPlainName().equals("snob")) {
                if (sourcesForUnit == null) {
                    snobSources = 0;
                } else {
                    snobSources = sourcesForUnit.size();
                }
            }
            if (sourcesForUnit == null) {
                sourcesForUnit = new LinkedList<Village>();
                sourcesForUnit.add(vSource);
                sources.put(uSource, sourcesForUnit);
            } else {
                sourcesForUnit.add(vSource);
            }
        } else {
            List<Village> fakesForUnit = fakes.get(uSource);
            if (fakesForUnit == null) {
                fakesForUnit = new LinkedList<Village>();
                fakesForUnit.add(vSource);
                fakes.put(uSource, fakesForUnit);
            } else {
                fakesForUnit.add(vSource);
            }
        }
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc=" Check for units not supported by the algorithm">
    boolean useMiscUnits = false;
    Enumeration<UnitHolder> involvedUnits = sources.keys();
    while (involvedUnits.hasMoreElements()) {
        UnitHolder u = involvedUnits.nextElement();
        //check for misc unit
        if (!u.getPlainName().equals("ram") && !u.getPlainName().equals("catapult")) {
            useMiscUnits = true;
            break;
        }
    }
    if (!useMiscUnits) {
        involvedUnits = fakes.keys();
        while (involvedUnits.hasMoreElements()) {
            UnitHolder u = involvedUnits.nextElement();
            //check for misc unit
            if (!u.getPlainName().equals("ram") && !u.getPlainName().equals("catapult")) {
                useMiscUnits = true;
                break;
            }
        }
    }
    // </editor-fold>
    boolean fakeOffTargets = mSettingsPanel.fakeOffTargets();
    //mSettingsPanel.getAttacksPerVillage();
    TimeFrame timeFrame = mSettingsPanel.getTimeFrame();
    //start processing
    AbstractAttackAlgorithm algo = null;
    boolean supportMiscUnits = false;
    if (mSettingsPanel.useBruteForce()) {
        logger.info("Using 'BruteForce' calculation");
        algo = new BruteForce();
        //algo = new Recurrection();
        supportMiscUnits = true;
        logPanel.setAbortable(false);
    } else {
        logger.info("Using 'systematic' calculation");
        algo = new Iterix();
        supportMiscUnits = false;
        logPanel.setAbortable(true);
    }
    //check misc-units criteria
    if (useMiscUnits && !supportMiscUnits) {
        if (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Der gewhlte Algorithmus untersttzt nur Rammen und Katapulte als angreifende Einheiten.\n"
                        + "Drfer fr die eine andere Einheit gewhlt wurde werden ignoriert.\n"
                        + "Trotzdem fortfahren?",
                "Warnung", "Nein", "Ja") == JOptionPane.NO_OPTION) {
            logger.debug("User aborted calculation due to algorithm");
            return;
        }
    }
    mSettingsPanel.storeProperties();
    logPanel.clear();
    algo.initialize(sources, fakes, victimVillages, victimVillagesFaked, maxAttacksTable, timeFrame,
            fakeOffTargets, logPanel);
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            try {
                jCalculateButton.setEnabled(false);
                mLogFrame.setVisible(true);
                mLogFrame.toFront();
            } catch (Exception e) {
            }
        }
    });
    algo.execute(this);
}

From source file:interfaces.InterfazPrincipal.java

private void botonRegistrarAbonoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonRegistrarAbonoActionPerformed
    // TODO add your handling code here:
    try {/*from   ww  w.  j av  a2s .co m*/

        String identificacionCliente = mostrarIdentificacionCliente.getText();
        Double abono = Double.parseDouble(abonoClente.getText());

        if (abono <= 0.0) {
            throw new Exception();
        }

        ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
        ControladorFactura controladorFactura = new ControladorFactura();

        Calendar calendario = Calendar.getInstance();
        String dia = Integer.toString(calendario.get(Calendar.DATE));
        String mes = Integer.toString(calendario.get(Calendar.MONTH));
        String annio = Integer.toString(calendario.get(Calendar.YEAR));
        Date date = new Date();
        DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
        String hora = hourFormat.format(date);

        String fecha = annio + "-" + mes + "-" + dia + " " + hora;
        /*
         * -----------------Tomar el abono y los pagos-----------------
         * Procedimiento
         * 1 Tomar flujos de deuda de cada factura con estado fiado
         * 2 Tomar abonos de abono de cada factura con estado fiado
         * 3 Calcular la resta de estos dos para deteminar lo que se debe por factura
         * 4 Cancelar con el flujo la factura y si lo debido es 0 colocar estado pagado
         * 5 Mostrar una informacin en un JOptionPane y recalcular la deuda
         * 
         */
        DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoClientes.getModel();
        ArrayList<String> codigoFactura = new ArrayList<>();
        ArrayList<Double> totalDebe = new ArrayList<>();

        JTextArea area = new JTextArea(10, 30);
        String informe = "\t Registro flujo pago del abono \n\n";
        informe += "Factura \t Pago \t Queda pagada? \n\n";

        int numeroRegistros = -1;
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            //System.out.println("Entro al for " + i);
            //Se necesita 0: Factura ID, 1 Tipo, 3 Valor
            // Codigofactura contiene los cogidos de las facturas
            // totalDebe contiene lo que debe de las facturas, la posicion coincide con la lista CodigoFactura
            String factura_id = String.valueOf(modeloClientes.getValueAt(i, 0));
            String tipo_flujo = String.valueOf(modeloClientes.getValueAt(i, 1));
            Double valor = Double.parseDouble(String.valueOf(modeloClientes.getValueAt(i, 3)));
            if (codigoFactura.contains(factura_id)) {

                if (tipo_flujo.equals("abono")) {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) - valor);
                } else {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) + valor);
                }
            } else {
                numeroRegistros++;
                codigoFactura.add(factura_id);
                if (tipo_flujo.equals("abono")) {
                    totalDebe.add(-valor);
                } else {
                    totalDebe.add(valor);
                }
            }

        }
        //System.out.println(Arrays.toString(codigoFactura.toArray()));
        //System.out.println(Arrays.toString(totalDebe.toArray()));
        Double debeTotal = 0d;
        for (int i = 0; i < totalDebe.size(); i++) {
            debeTotal += totalDebe.get(i);

        }

        if (debeTotal < abono) {
            JOptionPane.showMessageDialog(this,
                    "El monto es superior a lo que debe el cliente, por favor indique otro monto", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        for (int i = 0; i < totalDebe.size(); i++) {
            //Tomar flujos
            if (abono > 0.0) {
                Double pago = totalDebe.get(i) - abono;

                //Pago igual a 0 significa que se pag la factura
                if (pago == 0) {
                    //Registrar flujo
                    String[] value = { codigoFactura.get(i), "abono", fecha, String.valueOf(abono) };
                    //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                    controladorFlujoFactura.insertFlujo_Factura(value);

                    controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                    informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                    //Romper el for
                    break;
                } else {

                    //Pago mayor que 0, es decir se queda debiendo
                    if (pago > 0) {

                        //Registrar flujo
                        String[] value = { codigoFactura.get(i), "abono", fecha, String.valueOf(abono) };
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.insertFlujo_Factura(value);
                        //Como el abono ahora es menor que 0 debe romperse el for
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tNO\n";

                        break;

                    } else {
                        //Caso final pago menor 0, es decir el abono paga la factura pero queda disponible para otras facturas
                        //Registrar flujo
                        String[] value = { codigoFactura.get(i), "abono", fecha,
                                String.valueOf(totalDebe.get(i)) };
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.insertFlujo_Factura(value);

                        controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");

                        //Ajustamos ahora el abono restando lo que debe la factura
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                        abono -= totalDebe.get(i);
                    }

                }
            } else {
                //Romper el for
                break;
            }

        }

        //Reordenar y volver a consultar
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            modeloClientes.removeRow(i);
        }

        modeloClientes.setRowCount(0);

        //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
        ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                " where factura_id in (select factura_id from Factura where cliente_id = "
                        + String.valueOf(identificacionCliente) + " and estado=\"fiado\") order by factura_id");
        double pago = 0.0;

        for (int i = 0; i < flujosCliente.size(); i++) {
            String[] datos = flujosCliente.get(i);
            Object[] rowData = { datos[1], datos[2], datos[3], datos[4] };
            modeloClientes.addRow(rowData);
            if (datos[2].equals("deuda")) {
                pago += Double.parseDouble(datos[4]);
            } else {
                pago -= Double.parseDouble(datos[4]);
            }
        }

        textoTotalDebe.setText(String.valueOf(pago));
        TablaDeSaldoClientes.setModel(modeloClientes);
        area.setText(informe);
        JScrollPane panelInformePago = new JScrollPane(area);
        JOptionPane.showMessageDialog(this, panelInformePago);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe ingresar un valor numrico mayor que 0 en el abono ");
    }
}

From source file:interfaces.InterfazPrincipal.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    // TODO add your handling code here:

    try {// w w  w .  j  ava2  s  .c  om

        String identificacionCliente = mostrarIDProveedor.getText();
        Double abono = Double.parseDouble(jTextFieldAbonoProveedor.getText());

        if (abono <= 0.0 || identificacionCliente.equals("")) {
            throw new Exception();
        }

        ControladorFlujoCompras controladorFlujoFactura = new ControladorFlujoCompras();
        ControladorCompraProveedor controladorCompraProveedor = new ControladorCompraProveedor();

        Calendar calendario = Calendar.getInstance();
        String dia = Integer.toString(calendario.get(Calendar.DATE));
        String mes = Integer.toString(calendario.get(Calendar.MONTH));
        String annio = Integer.toString(calendario.get(Calendar.YEAR));
        Date date = new Date();
        DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
        String hora = hourFormat.format(date);

        String fecha = annio + "-" + mes + "-" + dia + " " + hora;
        /*
         * -----------------Tomar el abono y los pagos-----------------
         * Procedimiento
         * 1 Tomar flujos de deuda de cada factura con estado fiado
         * 2 Tomar abonos de abono de cada factura con estado fiado
         * 3 Calcular la resta de estos dos para deteminar lo que se debe por factura
         * 4 Cancelar con el flujo la factura y si lo debido es 0 colocar estado pagado
         * 5 Mostrar una informacin en un JOptionPane y recalcular la deuda
         * 
         */
        DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoProveedor.getModel();
        ArrayList<String> codigoFactura = new ArrayList<>();
        ArrayList<Double> totalDebe = new ArrayList<>();

        JTextArea area = new JTextArea(10, 30);
        String informe = "\t Registro flujo pago del abono \n\n";
        informe += "Factura \t Pago \t Queda pagada? \n\n";

        int numeroRegistros = -1;
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            //System.out.println("Entro al for " + i);
            //Se necesita 0: Factura ID, 1 Tipo, 3 Valor
            // Codigofactura contiene los cogidos de las facturas
            // totalDebe contiene lo que debe de las facturas, la posicion coincide con la lista CodigoFactura
            String factura_id = String.valueOf(modeloClientes.getValueAt(i, 0));
            String tipo_flujo = String.valueOf(modeloClientes.getValueAt(i, 1));
            Double valor = Double.parseDouble(String.valueOf(modeloClientes.getValueAt(i, 3)));
            if (codigoFactura.contains(factura_id)) {

                if (tipo_flujo.equals("abono")) {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) - valor);
                } else {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) + valor);
                }
            } else {
                numeroRegistros++;
                codigoFactura.add(factura_id);
                if (tipo_flujo.equals("abono")) {
                    totalDebe.add(-valor);
                } else {
                    totalDebe.add(valor);
                }
            }

        }
        //System.out.println(Arrays.toString(codigoFactura.toArray()));
        //System.out.println(Arrays.toString(totalDebe.toArray()));
        System.out.println(totalDebe);
        double debeTotal = 0d;
        for (int i = 0; i < totalDebe.size(); i++) {
            debeTotal += totalDebe.get(i);
        }

        if (debeTotal < abono) {
            JOptionPane.showMessageDialog(this, "El monto a pagar no puede ser superior a lo que se debe",
                    "Error del sistema", JOptionPane.ERROR_MESSAGE);
            return;
        }
        for (int i = 0; i < totalDebe.size(); i++) {
            //Tomar flujos
            if (abono > 0.0) {
                Double pago = totalDebe.get(i) - abono;

                //Pago igual a 0 significa que se pag la factura
                if (pago == 0) {
                    //Registrar flujo
                    //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(abono)};
                    //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                    controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i), String.valueOf(abono));

                    //controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                    informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                    //Romper el for
                    break;
                } else {

                    //Pago mayor que 0, es decir se queda debiendo
                    if (pago > 0) {

                        //Registrar flujo
                        //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(abono)};
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i),
                                String.valueOf(abono));
                        //Como el abono ahora es menor que 0 debe romperse el for
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tNO\n";

                        break;

                    } else {
                        //Caso final pago menor 0, es decir el abono paga la factura pero queda disponible para otras facturas
                        //Registrar flujo
                        //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(totalDebe.get(i))};
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i),
                                String.valueOf(totalDebe.get(i)));

                        //controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                        //Ajustamos ahora el abono restando lo que debe la factura
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                        abono -= totalDebe.get(i);
                    }

                }
            } else {
                //Romper el for
                break;
            }

        }

        //Reordenar y volver a consultar
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            modeloClientes.removeRow(i);
        }

        modeloClientes.setRowCount(0);

        //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
        ArrayList<Flujo_Compra> flujosProveedor = controladorFlujoFactura.obtenerFlujosCompras(
                " where ID_CompraProveedor in (select ID_CompraProveedor from Compra_Proveedores where IDProveedor = "
                        + String.valueOf(identificacionCliente) + ") order by ID_CompraProveedor");
        double pago = 0.0;

        for (int i = 0; i < flujosProveedor.size(); i++) {
            Flujo_Compra datos = flujosProveedor.get(i);
            Object[] rowData = { datos.getID_CompraProveedor(), datos.getTipo_flujo(), datos.getFecha(),
                    datos.getMonto() };

            if (datos.getTipo_flujo().equals("deuda")) {
                pago += Double.parseDouble(datos.getMonto() + "");
            } else {
                pago -= Double.parseDouble(datos.getMonto() + "");
            }

            modeloClientes.addRow(rowData);
        }

        TablaDeSaldoProveedor.setModel(modeloClientes);
        deudaActualProveedor.setText(String.valueOf(pago));

        //Mostrar en table de clientes los datos
        botonRegistrarAbono.setEnabled(true);

        area.setText(informe);
        JScrollPane panelInformePago = new JScrollPane(area);
        JOptionPane.showMessageDialog(this, panelInformePago);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe ingresar un valor numrico mayor que 0 en el abono ");
    }

}

From source file:captureplugin.CapturePlugin.java

/**
 * Check the programs after data update.
 *///from w  ww.  ja  v  a 2  s . c  om
public void handleTvDataUpdateFinished() {
    mNeedsUpdate = true;

    if (mAllowedToShowDialog) {
        mNeedsUpdate = false;

        DeviceIf[] devices = mConfig.getDeviceArray();

        final DefaultTableModel model = new DefaultTableModel() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        model.setColumnCount(5);
        model.setColumnIdentifiers(new String[] { mLocalizer.msg("device", "Device"),
                Localizer.getLocalization(Localizer.I18N_CHANNEL), mLocalizer.msg("date", "Date"),
                ProgramFieldType.START_TIME_TYPE.getLocalizedName(),
                ProgramFieldType.TITLE_TYPE.getLocalizedName() });

        JTable table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.getTableHeader().setResizingAllowed(false);
        table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable renderTable, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(renderTable, value, isSelected, hasFocus, row,
                        column);

                if (value instanceof DeviceIf) {
                    if (((DeviceIf) value).getDeleteRemovedProgramsAutomatically() && !isSelected) {
                        c.setForeground(Color.red);
                    }
                }

                return c;
            }
        });

        int[] columnWidth = new int[5];

        for (int i = 0; i < columnWidth.length; i++) {
            columnWidth[i] = UiUtilities.getStringWidth(table.getFont(), model.getColumnName(i)) + 10;
        }

        for (DeviceIf device : devices) {
            Program[] deleted = device.checkProgramsAfterDataUpdateAndGetDeleted();

            if (deleted != null && deleted.length > 0) {
                for (Program p : deleted) {
                    if (device.getDeleteRemovedProgramsAutomatically() && !p.isExpired() && !p.isOnAir()) {
                        device.remove(UiUtilities.getLastModalChildOf(getParentFrame()), p);
                    } else {
                        device.removeProgramWithoutExecution(p);
                    }

                    if (!p.isExpired()) {
                        Object[] o = new Object[] { device, p.getChannel().getName(), p.getDateString(),
                                p.getTimeString(), p.getTitle() };

                        for (int i = 0; i < columnWidth.length; i++) {
                            columnWidth[i] = Math.max(columnWidth[i],
                                    UiUtilities.getStringWidth(table.getFont(), o[i].toString()) + 10);
                        }

                        model.addRow(o);
                    }
                }
            }

            device.getProgramList();
        }

        if (model.getRowCount() > 0) {
            int sum = 0;

            for (int i = 0; i < columnWidth.length; i++) {
                table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);

                if (i < columnWidth.length - 1) {
                    table.getColumnModel().getColumn(i).setMaxWidth(columnWidth[i]);
                }

                sum += columnWidth[i];
            }

            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(450, 250));

            if (sum > 500) {
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                scrollPane.getViewport().setPreferredSize(
                        new Dimension(sum, scrollPane.getViewport().getPreferredSize().height));
            }

            JButton export = new JButton(mLocalizer.msg("exportList", "Export list"));
            export.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setFileFilter(new FileFilter() {
                        public boolean accept(File f) {
                            return f.isDirectory() || f.toString().toLowerCase().endsWith(".txt");
                        }

                        public String getDescription() {
                            return "*.txt";
                        }
                    });

                    chooser.setSelectedFile(new File("RemovedPrograms.txt"));
                    if (chooser.showSaveDialog(
                            UiUtilities.getLastModalChildOf(getParentFrame())) == JFileChooser.APPROVE_OPTION) {
                        if (chooser.getSelectedFile() != null) {
                            String file = chooser.getSelectedFile().getAbsolutePath();

                            if (!file.toLowerCase().endsWith(".txt") && file.indexOf('.') == -1) {
                                file = file + ".txt";
                            }

                            if (file.indexOf('.') != -1) {
                                try {
                                    RandomAccessFile write = new RandomAccessFile(file, "rw");
                                    write.setLength(0);

                                    String eolStyle = File.separator.equals("/") ? "\n" : "\r\n";

                                    for (int i = 0; i < model.getRowCount(); i++) {
                                        StringBuilder line = new StringBuilder();

                                        for (int j = 0; j < model.getColumnCount(); j++) {
                                            line.append(model.getValueAt(i, j)).append(' ');
                                        }

                                        line.append(eolStyle);

                                        write.writeBytes(line.toString());
                                    }

                                    write.close();
                                } catch (Exception ee) {
                                }
                            }
                        }
                    }
                }
            });

            Object[] message = {
                    mLocalizer.msg("deletedText",
                            "The data was changed and the following programs were deleted:"),
                    scrollPane, export };

            JOptionPane pane = new JOptionPane();
            pane.setMessage(message);
            pane.setMessageType(JOptionPane.PLAIN_MESSAGE);

            final JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(getParentFrame()),
                    mLocalizer.msg("CapturePlugin", "CapturePlugin") + " - "
                            + mLocalizer.msg("deletedTitle", "Deleted programs"));
            d.setResizable(true);
            d.setModal(false);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    d.setVisible(true);
                }
            });
        }
    }
}

From source file:interfaces.InterfazPrincipal.java

private void TablaDeFacturaProductoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaDeFacturaProductoMouseClicked
    final int fila = TablaDeFacturaProducto.getSelectedRow();
    final DefaultTableModel modeloTabla = (DefaultTableModel) TablaDeFacturaProducto.getModel();

    //int identificacion = (int) TablaDeFacturaProducto.getValueAt(fila, 0);        // TODO add your handling code here:
    final JDialog dialogoEdicionProducto = new JDialog(this);
    dialogoEdicionProducto.setTitle("Editar producto");
    dialogoEdicionProducto.setSize(250, 150);
    dialogoEdicionProducto.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel editarTextoPrincipalDialogo = new JLabel("Editar producto");
    c.gridx = 0;/*  w  w w  .ja v a2  s.co  m*/
    c.gridy = 0;
    c.gridwidth = 3;
    c.insets = new Insets(15, 40, 10, 0);
    Font textoGrande = new Font("Arial", 1, 18);
    editarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(editarTextoPrincipalDialogo, c);

    c.insets = new Insets(0, 0, 0, 0);
    c.gridwidth = 0;

    c.gridy = 1;
    c.gridx = 0;
    JLabel textoUnidades = new JLabel("Unidades");
    panelDialogo.add(textoUnidades, c);

    c.gridy = 1;
    c.gridx = 1;
    c.gridwidth = 2;
    final JTextField valorUnidades = new JTextField();
    valorUnidades.setText(String.valueOf(modeloTabla.getValueAt(fila, 4)));

    panelDialogo.add(valorUnidades, c);

    c.gridwidth = 1;
    c.gridy = 2;
    c.gridx = 0;
    JButton guardarCambios = new JButton("Guardar");
    panelDialogo.add(guardarCambios, c);

    c.gridy = 2;
    c.gridx = 1;
    JButton eliminarProducto = new JButton("Eliminar");
    panelDialogo.add(eliminarProducto, c);

    c.gridy = 2;
    c.gridx = 2;
    JButton botonCancelar = new JButton("Cerrar");
    panelDialogo.add(botonCancelar, c);
    botonCancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEdicionProducto.dispose();
        }
    });

    eliminarProducto.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            double precio = (double) modeloTabla.getValueAt(fila, 6);
            double precioActual = Double.parseDouble(valorActualFactura.getText());

            precioActual -= precio;
            valorActualFactura.setText(String.valueOf(precioActual));
            modeloTabla.removeRow(fila);

            dialogoEdicionProducto.dispose();

        }
    });
    guardarCambios.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int numeroUnidades = Integer.parseInt(valorUnidades.getText());
                modeloTabla.setValueAt(numeroUnidades, fila, 4);

                double precioARestar = (double) modeloTabla.getValueAt(fila, 6);

                double valorUnitario = Double.parseDouble((String) modeloTabla.getValueAt(fila, 5));

                double precioNuevo = valorUnitario * numeroUnidades;

                modeloTabla.setValueAt(precioNuevo, fila, 6);
                double precioActual = Double.parseDouble(valorActualFactura.getText());
                precioActual -= precioARestar;
                precioActual += precioNuevo;
                valorActualFactura.setText(String.valueOf(precioActual));

                dialogoEdicionProducto.dispose();

            } catch (Exception eve) {
                JOptionPane.showMessageDialog(dialogoEdicionProducto, "Por favor ingrese un valor numrico");
            }
        }
    });

    dialogoEdicionProducto.add(panelDialogo);
    dialogoEdicionProducto.setVisible(true);
}

From source file:interfaces.InterfazPrincipal.java

private void botonGenerarReporteClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGenerarReporteClienteActionPerformed
    // TODO add your handling code here:
    try {/*from   www  . j  a va2  s . c  o m*/
        if (clienteReporteClienteFechaFinal.getSelectedDate().getTime()
                .compareTo(clienteReporteClienteFechaInicial.getSelectedDate().getTime()) < 0) {
            JOptionPane.showMessageDialog(this, "La fecha final debe ser posterior al dia de inicio");
        } else {
            final ArrayList<Integer> listaIDFlujos = new ArrayList<>();
            final JDialog dialogoEditar = new JDialog();
            dialogoEditar.setTitle("Reporte cliente");
            dialogoEditar.setSize(350, 610);
            dialogoEditar.setResizable(false);

            JPanel panelDialogo = new JPanel();
            panelDialogo.setLayout(new GridBagLayout());

            GridBagConstraints c = new GridBagConstraints();
            //c.fill = GridBagConstraints.HORIZONTAL;

            JLabel ediitarTextoPrincipalDialogo = new JLabel("Informe cliente");
            c.gridx = 0;
            c.gridy = 0;
            c.gridwidth = 1;
            c.insets = new Insets(10, 45, 10, 10);
            Font textoGrande = new Font("Arial", 1, 18);
            ediitarTextoPrincipalDialogo.setFont(textoGrande);
            panelDialogo.add(ediitarTextoPrincipalDialogo, c);

            final JTable tablaDialogo = new JTable();
            DefaultTableModel modeloTabla = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    //all cells false
                    return false;
                }
            };
            ;

            modeloTabla.addColumn("Factura");
            modeloTabla.addColumn("Tipo Flujo");
            modeloTabla.addColumn("Fecha");
            modeloTabla.addColumn("Valor");

            //Llenar tabla
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                    " where factura_id in (select factura_id from Factura where cliente_id = "
                            + String.valueOf(jTextFieldIdentificacionClienteReporte.getText())
                            + ") order by factura_id");
            // {"flujo_id","factura_id","tipo_flujo","fecha","valor"};
            ArrayList<Calendar> fechasFlujos = new ArrayList<>();

            for (int i = 0; i < flujosCliente.size(); i++) {
                String fila[] = new String[4];
                String[] objeto = flujosCliente.get(i);
                fila[0] = objeto[1];
                fila[1] = objeto[2];
                fila[2] = objeto[3];
                fila[3] = objeto[4];

                //Filtrar, mirar las fechas
                String[] partirEspacios = objeto[3].split("\\s");
                //El primer string es la fecha sin hora
                //Ahora esparamos por -
                String[] tomarAgeMesDia = partirEspacios[0].split("-");

                //Realizar filtro
                int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]);
                int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]);
                int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]);

                //Obtenemos dias, mes y ao de la consulta
                //Inicial
                int anioInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.YEAR);
                int mesInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.DAY_OF_MONTH);
                //Final
                int anioFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.YEAR);
                int mesFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.DAY_OF_MONTH);

                //Construir fechas
                Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta);
                //Set year, month, day)

                Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial);
                Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal);

                if (fechaDeLaBD.compareTo(fechaInicialRango) <= 0
                        && fechaDeLaBD.compareTo(fechaFinalRango) >= 0) {
                    fechasFlujos.add(fechaDeLaBD);
                    modeloTabla.addRow(fila);
                }

            }

            if (modeloTabla.getRowCount() > 0) {
                tablaDialogo.setModel(modeloTabla);
                tablaDialogo.getColumn("Factura").setMinWidth(80);
                tablaDialogo.getColumn("Tipo Flujo").setMinWidth(80);
                tablaDialogo.getColumn("Fecha").setMinWidth(90);
                tablaDialogo.getColumn("Valor").setMinWidth(80);
                tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                JScrollPane scroll = new JScrollPane(tablaDialogo);
                scroll.setPreferredSize(new Dimension(330, 150));

                c.gridx = 0;
                c.gridy = 1;
                c.gridwidth = 1;
                c.insets = new Insets(0, 0, 0, 0);
                panelDialogo.add(scroll, c);

                TimeSeries localTimeSeries = new TimeSeries("Compras del cliente en el periodo");

                Map listaAbonos = new HashMap();

                for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                    listaIDFlujos.add(Integer.parseInt(flujosCliente.get(i)[0]));

                    if (modeloTabla.getValueAt(i, 1).equals("abono")) {
                        Calendar fechaFlujo = fechasFlujos.get(i);
                        double valor = Double.parseDouble(String.valueOf(modeloTabla.getValueAt(i, 3)));

                        int anoDato = fechaFlujo.get(Calendar.YEAR);
                        int mesDato = fechaFlujo.get(Calendar.MONTH) + 1;
                        int diaDato = fechaFlujo.get(Calendar.DAY_OF_MONTH);
                        Day FechaDato = new Day(diaDato, mesDato, anoDato);

                        if (listaAbonos.get(FechaDato) != null) {
                            double valorAbono = (double) listaAbonos.get(FechaDato);
                            listaAbonos.remove(FechaDato);
                            listaAbonos.put(FechaDato, valorAbono + valor);
                        } else {
                            listaAbonos.put(FechaDato, valor);

                        }

                    }

                }
                Double maximo = 0.0;
                Iterator iterator = listaAbonos.keySet().iterator();
                while (iterator.hasNext()) {
                    Day key = (Day) iterator.next();
                    Double value = (double) listaAbonos.get(key);
                    maximo = Math.max(maximo, value);
                    localTimeSeries.add(key, value);
                }

                //localTimeSeries.add();
                TimeSeriesCollection datos = new TimeSeriesCollection(localTimeSeries);

                JFreeChart chart = ChartFactory.createTimeSeriesChart("Compras del cliente en el periodo", // Title
                        "Tiempo", // x-axis Label
                        "Total ($)", // y-axis Label
                        datos, // Dataset
                        true, // Show Legend
                        true, // Use tooltips
                        false // Configure chart to generate URLs?
                );
                /*Altering the graph */
                XYPlot plot = (XYPlot) chart.getPlot();
                plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0));
                plot.setDomainCrosshairVisible(true);
                plot.setRangeCrosshairVisible(true);

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
                renderer.setBaseShapesVisible(true);
                renderer.setBaseShapesFilled(true);

                NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
                numberAxis.setRange(new Range(0, maximo * 1.2));
                Font font = new Font("Dialog", Font.PLAIN, 9);
                numberAxis.setTickLabelFont(font);
                numberAxis.setLabelFont(font);

                DateAxis axis = (DateAxis) plot.getDomainAxis();
                axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
                axis.setAutoTickUnitSelection(false);
                axis.setVerticalTickLabels(true);

                axis.setTickLabelFont(font);
                axis.setLabelFont(font);

                LegendTitle leyendaChart = chart.getLegend();
                leyendaChart.setItemFont(font);

                Font fontTitulo = new Font("Dialog", Font.BOLD, 12);
                TextTitle tituloChart = chart.getTitle();
                tituloChart.setFont(fontTitulo);

                ChartPanel CP = new ChartPanel(chart);
                Dimension D = new Dimension(330, 300);
                CP.setPreferredSize(D);
                CP.setVisible(true);
                c.gridx = 0;
                c.gridy = 2;
                c.gridwidth = 1;
                c.insets = new Insets(10, 0, 0, 0);
                panelDialogo.add(CP, c);

                c.gridx = 0;
                c.gridy = 3;
                c.gridwidth = 1;
                c.anchor = GridBagConstraints.WEST;
                c.insets = new Insets(10, 30, 0, 0);

                JButton botonCerrar = new JButton("Cerrar");
                botonCerrar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialogoEditar.dispose();
                    }
                });
                panelDialogo.add(botonCerrar, c);

                JButton botonGenerarPDF = new JButton("Guardar archivo");
                botonGenerarPDF.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.guardarDocumentoDialogo(dialogoEditar, listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 100, 0, 0);

                panelDialogo.add(botonGenerarPDF, c);

                JButton botonImprimir = new JButton("Imprimir");
                botonImprimir.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.imprimirFlujo(listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 230, 0, 0);

                panelDialogo.add(botonImprimir, c);
                dialogoEditar.add(panelDialogo);

                dialogoEditar.setVisible(true);

            } else {
                JOptionPane.showMessageDialog(this,
                        "El cliente no registra movimientos en el rango de fechas seleccionado");
            }

        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe seleccionar un da inicial y final de fechas");
    }

}

From source file:edu.ku.brc.specify.conversion.GenericDBConversion.java

/**
 * @return//  w  w  w .  j a v a2s.  com
 */
public CollectionResultType initialize() {

    collectionInfoList = CollectionInfo.getCollectionInfoList(oldDBConn, false);
    //fixIdaho();
    if (collectionInfoList == null) {
        if (CollectionInfo.isAskForFix()) {
            if (ConvertTaxonHelper.fixTaxonomicUnitType(oldDBConn)) {
                collectionInfoList = CollectionInfo.getCollectionInfoList(oldDBConn, true);
            } else {
                try {
                    oldDBConn.close();
                } catch (SQLException e) {
                }
                System.exit(0);
            }
        } else {
            try {
                oldDBConn.close();
            } catch (SQLException e) {
            }
            System.exit(0);
        }
    }

    collectionInfoShortList = CollectionInfo.getFilteredCollectionInfoList();

    if (collectionInfoList != null && collectionInfoList.size() > 0) {
        int paleoCnt = 0;

        // This is a Hash of TaxonObjectType to see how many collections use the same TaxonObjectType
        HashMap<Integer, HashSet<CollectionInfo>> taxonomyTypeHash = new HashMap<Integer, HashSet<CollectionInfo>>();

        // Get a List for each type of Paleo Collection, hashed by the Root Id
        HashMap<Integer, Vector<CollectionInfo>> paleoColInfoHash = new HashMap<Integer, Vector<CollectionInfo>>();
        HashMap<Integer, HashSet<DisciplineType.STD_DISCIPLINES>> paleoDispTypeHash = new HashMap<Integer, HashSet<DisciplineType.STD_DISCIPLINES>>();

        for (CollectionInfo colInfo : collectionInfoShortList) {
            // Tracks a 'set' of CollectionInfo objects for each TaxonomyTypeId
            HashSet<CollectionInfo> taxonomyTypeSet = taxonomyTypeHash.get(colInfo.getTaxonomyTypeId());
            if (taxonomyTypeSet == null) {
                System.out.println("Creating TxTypeID: " + colInfo.getTaxonomyTypeId() + "  From "
                        + colInfo.getCatSeriesName());

                taxonomyTypeSet = new HashSet<CollectionInfo>();
                taxonomyTypeHash.put(colInfo.getTaxonomyTypeId(), taxonomyTypeSet);
            } else {
                System.out.println("Adding TxTypeID: " + colInfo.getTaxonomyTypeId() + "  From "
                        + colInfo.getCatSeriesName() + "  " + taxonomyTypeSet.size());
            }
            taxonomyTypeSet.add(colInfo);

            //---
            DisciplineType dType = getStandardDisciplineName(colInfo.getTaxonomyTypeName(),
                    colInfo.getColObjTypeName(), colInfo.getCatSeriesName());
            colInfo.setDisciplineTypeObj(dType);

            if (dType != null && dType.isPaleo()) {
                Vector<CollectionInfo> ciList = paleoColInfoHash.get(colInfo.getTaxonNameId());
                if (ciList == null) {
                    ciList = new Vector<CollectionInfo>();
                    paleoColInfoHash.put(colInfo.getTaxonNameId(), ciList);
                }
                ciList.add(colInfo);

                HashSet<DisciplineType.STD_DISCIPLINES> typeDispSet = paleoDispTypeHash
                        .get(colInfo.getTaxonNameId());
                if (typeDispSet == null) {
                    typeDispSet = new HashSet<DisciplineType.STD_DISCIPLINES>();
                    paleoDispTypeHash.put(colInfo.getTaxonNameId(), typeDispSet);
                }
                typeDispSet.add(colInfo.getDisciplineTypeObj().getDisciplineType());

                paleoCnt++;
            }
            System.out.println("--------------------------------------");
            //System.out.println(colInfo.toString()+"\n");
        } // for loop

        int cnt = 0;
        StringBuilder msg = new StringBuilder();
        for (Integer taxonomyTypId : taxonomyTypeHash.keySet()) {
            HashSet<CollectionInfo> taxonomyTypeSet = taxonomyTypeHash.get(taxonomyTypId);
            if (taxonomyTypeSet.size() > 1) {
                msg.append(
                        String.format("<html>TaxonomyTypeId %d has more than one Discpline/Collection:<br><OL>",
                                taxonomyTypId));
                for (CollectionInfo ci : taxonomyTypeSet) {
                    msg.append(String.format("<LI>%s - %s - %s</LI>", ci.getCatSeriesName(),
                            ci.getColObjTypeName(), ci.getTaxonomyTypeName()));
                }
                msg.append("</OL>");
                cnt++;
            }
        }

        if (cnt > 0) {
            JOptionPane.showConfirmDialog(null, msg.toString(), "Taxomony Type Issues",
                    JOptionPane.CLOSED_OPTION, JOptionPane.QUESTION_MESSAGE);
        }

        // Will be zero for no Paleo collections
        if (paleoCnt > 1) {
            // Check to see if they all use the same tree
            if (paleoColInfoHash.size() > 1) {
                msg.setLength(0);
                // We get here when there is more than one Taxon Tree for the Paleo Collections
                for (Integer treeId : paleoColInfoHash.keySet()) {
                    Vector<CollectionInfo> ciList = paleoColInfoHash.get(treeId);
                    CollectionInfo colInfo = ciList.get(0);
                    msg.append(String.format("The following collections use Taxon Tree '%s':\n",
                            colInfo.getTaxonomyTypeName()));
                    for (CollectionInfo ci : paleoColInfoHash.get(treeId)) {
                        DisciplineType dType = getStandardDisciplineName(ci.getTaxonomyTypeName(),
                                ci.getColObjTypeName(), ci.getCatSeriesName());

                        String name = String.format("%s / %s / %s / %s / %s", ci.getCatSeriesPrefix(),
                                ci.getCatSeriesName(), ci.getColObjTypeName(), ci.getTaxonomyTypeName(),
                                dType.toString());
                        msg.append(name);
                        msg.append("\n");
                    }
                    msg.append("\n");
                }

                JOptionPane.showConfirmDialog(null, msg.toString(), "Paleo Taxon Tree Issues",
                        JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE);

            } else {
                StringBuilder colNames = new StringBuilder();
                for (Integer treeId : paleoColInfoHash.keySet()) {
                    for (CollectionInfo ci : paleoColInfoHash.get(treeId)) {
                        colNames.append("<LI>");
                        colNames.append(ci.getCatSeriesName());
                        colNames.append("</LI>");
                    }
                }

                // You get here when all the Paleo Disciplines use the same tree
                String msgStr = "<html>All the Paleo Collections need to use the same Taxon Tree and<br>therefore needs to be in the same discipline:<br><ol>";
                JOptionPane.showConfirmDialog(null, msgStr + colNames.toString(), "Paleo Taxon Tree Issues",
                        JOptionPane.CLOSED_OPTION, JOptionPane.QUESTION_MESSAGE);

                for (Integer treeId : paleoColInfoHash.keySet()) {
                    Vector<CollectionInfo> ciList = paleoColInfoHash.get(treeId);
                    CollectionInfo colInfo = ciList.get(0);
                    for (CollectionInfo ci : paleoColInfoHash.get(treeId)) {
                        ci.setDisciplineTypeObj(colInfo.getDisciplineTypeObj());
                    }
                }
            }
            //
        }

        DefaultTableModel model = CollectionInfo.getCollectionInfoTableModel(false);
        if (model.getRowCount() > 1) {
            TableWriter colInfoTblWriter = convLogger.getWriter("colinfo.html", "Collection Info");

            colInfoTblWriter.startTable();
            colInfoTblWriter.logHdr(CollectionInfoModel.getHeaders());

            Object[] row = new Object[model.getColumnCount()];
            for (int r = 0; r < model.getRowCount(); r++) {
                for (int i = 0; i < model.getColumnCount(); i++) {
                    row[i] = model.getValueAt(r, i);
                }
                colInfoTblWriter.logObjRow(row);
            }
            colInfoTblWriter.endTable();
            colInfoTblWriter.println("<BR><h3>Collections to be Created.</h3>");
            colInfoTblWriter.startTable();
            colInfoTblWriter.logHdr(CollectionInfoModel.getHeaders());

            model = CollectionInfo.getCollectionInfoTableModel(true);
            row = new Object[model.getColumnCount()];
            for (int r = 0; r < model.getRowCount(); r++) {
                for (int i = 0; i < model.getColumnCount(); i++) {
                    row[i] = model.getValueAt(r, i);
                }
                colInfoTblWriter.logObjRow(row);
            }
            colInfoTblWriter.endTable();
            colInfoTblWriter.close();

            File file = new File(colInfoTblWriter.getFileName());
            if (file != null && file.exists()) {
                try {
                    AttachmentUtils.openURI(file.toURI());

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        for (CollectionInfo ci : CollectionInfo.getFilteredCollectionInfoList()) {
            String sql = "select preparationmethod, ct.* from usyscollobjprepmeth pt inner join usysmetafieldsetsubtype st on st.fieldsetsubtypeid = pt.fieldsetsubtypeid "
                    + "inner join collectionobjecttype ct1 on ct1.collectionobjecttypeid = st.fieldvalue "
                    + "inner join collectionobjecttype ct on ct.collectionobjecttypename = replace(ct1.collectionobjecttypename, ' Preparation', '') "
                    + "inner join catalogseriesdefinition csd on csd.objecttypeid = ct.collectionobjecttypeid "
                    + "inner join catalogseries cs on cs.catalogseriesid = csd.catalogseriesid "
                    + "WHERE csd.catalogseriesid = " + ci.getCatSeriesId();

            System.out.println("\n------------------");
            System.out.println(ci.getCatSeriesName());
            System.out.println(sql);
            System.out.println("------------------");

            int i = 0;
            Vector<Object[]> list = BasicSQLUtils.query(oldDBConn, sql);
            if (list.size() > 0) {
                for (Object[] row : list) {
                    System.out.print(i + " - ");
                    for (Object col : row) {
                        System.out.print(col != null ? col.toString() : "null");
                        System.out.print(", ");
                    }
                    System.out.println();
                    i++;
                }
            } else {
                System.out.println("No Results");
            }

            sql = "select ct.*, (select relatedsubtypevalues from usysmetacontrol c "
                    + "left join usysmetafieldsetsubtype fst on fst.fieldsetsubtypeid = c.fieldsetsubtypeid "
                    + "where objectid = 10290 and ct.taxonomytypeid = c.relatedsubtypevalues) as DeterminationTaxonType "
                    + "from collectiontaxonomytypes ct where ct.biologicalobjecttypeid = "
                    + ci.getColObjTypeId();

            sql = String.format(
                    "SELECT CollectionTaxonomyTypesID, BiologicalObjectTypeID, CollectionObjectTypeName FROM (select ct.*, "
                            + "(SELECT distinct relatedsubtypevalues FROM usysmetacontrol c "
                            + "LEFT JOIN usysmetafieldsetsubtype fst ON fst.fieldsetsubtypeid = c.fieldsetsubtypeid "
                            + "WHERE objectid = 10290 AND ct.taxonomytypeid = c.relatedsubtypevalues) AS DeterminationTaxonType "
                            + "FROM collectiontaxonomytypes ct WHERE ct.biologicalobjecttypeid = %d) T1 "
                            + "INNER JOIN collectionobjecttype cot ON T1.biologicalobjecttypeid = cot.CollectionObjectTypeID",
                    ci.getColObjTypeId());

            System.out.println("\n------------------");
            System.out.println(ci.getColObjTypeName());
            System.out.println(sql);
            System.out.println("------------------");

            i = 0;
            list = BasicSQLUtils.query(oldDBConn, sql);
            if (list.size() > 0) {
                for (Object[] row : list) {
                    System.out.print(i + " - ");
                    for (Object col : row) {
                        System.out.print(col != null ? col.toString() : "null");
                        System.out.print(", ");
                    }
                    System.out.println();
                    i++;
                }
            } else {
                System.out.println("No Results");
            }
        }

        /*
                
        String sql = " select ct.*, (select relatedsubtypevalues from usysmetacontrol c " +
          "left join usysmetafieldsetsubtype fst on fst.fieldsetsubtypeid = c.fieldsetsubtypeid " +
          "where objectid = 10290 and ct.taxonomytypeid = c.relatedsubtypevalues) as DeterminationTaxonType " +
          "from collectiontaxonomytypes ct where ct.biologicalobjecttypeid = 13";
                
        System.out.println("\n------------------");
        System.out.println("List of the taxonomytypes associated with a CollectionObjectTypeID");
        System.out.println(sql);
        System.out.println("------------------");
                
        int i = 0;
        Vector<Object[]> list = BasicSQLUtils.query(oldDBConn, sql);
        if (list.size() > 0)
        {
        for (Object[] row : list)
        {
            System.out.print(i+" - ");
            for (Object col: row)
            {
                System.out.print(col != null ? col.toString() : "null");
                System.out.print(", ");
            }
            System.out.println();
        }
        } else
        {
        System.out.println("No Results");
        }*/

        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,2px,f:p:g,10px,p,2px,p:g,8px"));

        JTable tableTop = new JTable(CollectionInfo.getCollectionInfoTableModel(false));
        JTable tableBot = new JTable(
                CollectionInfo.getCollectionInfoTableModel(!CollectionInfo.DOING_ACCESSSION));

        int rows = 10;
        tableTop.setPreferredScrollableViewportSize(new Dimension(
                tableTop.getPreferredScrollableViewportSize().width, rows * tableTop.getRowHeight()));
        tableBot.setPreferredScrollableViewportSize(new Dimension(
                tableBot.getPreferredScrollableViewportSize().width, rows * tableBot.getRowHeight()));

        pb.add(UIHelper.createLabel("Available Specify 5 Taxononmic Types", SwingConstants.CENTER),
                cc.xy(1, 1));
        pb.add(UIHelper.createScrollPane(tableTop), cc.xy(1, 3));

        pb.add(UIHelper.createLabel("Specify 5 Collections to be Created", SwingConstants.CENTER), cc.xy(1, 5));
        pb.add(UIHelper.createScrollPane(tableBot), cc.xy(1, 7));

        pb.setDefaultDialogBorder();
        CustomDialog dlg = new CustomDialog(null, "Taxononic Types", true, pb.getPanel());
        dlg.createUI();

        dlg.setSize(1024, 500);

        UIHelper.centerWindow(dlg);
        dlg.setAlwaysOnTop(true);
        dlg.setVisible(true);

        if (dlg.isCancelled()) {
            return CollectionResultType.eCancel;
        }

        Pair<CollectionInfo, DisciplineType> pair = CollectionInfo.getDisciplineType(oldDBConn);
        if (pair == null || pair.second == null) {
            CollectionInfo colInfo = pair.first;
            disciplineType = getStandardDisciplineName(colInfo.getTaxonomyTypeName(),
                    colInfo.getColObjTypeName(), colInfo.getCatSeriesName());
        } else {
            disciplineType = pair.second;
        }

        return disciplineType != null ? CollectionResultType.eOK : CollectionResultType.eError;
    }
    return CollectionResultType.eError;
}

From source file:net.ytbolg.mcxa.ForgeCheck.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    DefaultTableModel newvm = (DefaultTableModel) jTable1.getModel();
    DefaultTableModel oldvm = (DefaultTableModel) jTable2.getModel();

    String mcver = "";
    String ver = "";
    System.out.println(jTabbedPane1.getSelectedIndex());
    switch (jTabbedPane1.getSelectedIndex()) {
    case 0: {/*w  ww .  ja v a 2  s.  co m*/
        //            System.out.println(jTable1.getValueAt(jTable1.getSelectedRow(), 0));
        //   System.out.println(jTable2.getSelectedRow());
        ver = newvm.getValueAt(jTable1.getSelectedRow(), 0).toString();
        mcver = newvm.getValueAt(jTable1.getSelectedRow(), 1).toString();
        System.out.println(ver + mcver);
        break;
        //    System.out.println(ver + mcver);
    }
    case 1: {
        ver = oldvm.getValueAt(jTable2.getSelectedRow(), 0).toString();
        mcver = oldvm.getValueAt(jTable2.getSelectedRow(), 1).toString();
        System.out.println(ver + mcver);
        break;
        // System.out.println(ver + mcver);
    }

    }
    DownloadForge.version = mcver;
    DownloadForge.forgeversion = ver;
    DownloadForge.j = jProgressBar1;
    DownloadForge.l = jLabel1;
    new Thread(new DownloadForge()).start(); // TODO add your handling code here:
}

From source file:net.ytbolg.mcxa.VersionCheck.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    DefaultTableModel zsbm = (DefaultTableModel) jTable1.getModel();
    DefaultTableModel kzbm = (DefaultTableModel) jTable2.getModel();
    DefaultTableModel jbbm = (DefaultTableModel) jTable3.getModel();
    DefaultTableModel qbm = (DefaultTableModel) jTable4.getModel();
    String version = "";
    switch (jTabbedPane1.getSelectedIndex()) {
    case 0:/* w  w w  . j  a va2 s .c  o m*/
        System.out.println(jTable1.getSelectedRow());
        version = zsbm.getValueAt(jTable1.getSelectedRow(), 0).toString();
        break;
    case 1:
        System.out.println(jTable2.getSelectedRow());
        version = kzbm.getValueAt(jTable2.getSelectedRow(), 0).toString();
        break;
    case 2:
        System.out.println(jTable3.getSelectedRow());
        version = jbbm.getValueAt(jTable3.getSelectedRow(), 0).toString();
        break;
    case 3:
        System.out.println(jTable4.getSelectedRow());
        version = qbm.getValueAt(jTable4.getSelectedRow(), 0).toString();
        break;

    }
    DownVersionThread.version = version;
    DownVersionThread.j = jProgressBar1;
    DownVersionThread.l = jLabel1;
    new Thread(new DownVersionThread()).start();
}