Example usage for javax.swing.table DefaultTableModel DefaultTableModel

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

Introduction

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

Prototype

public DefaultTableModel() 

Source Link

Document

Constructs a default DefaultTableModel which is a table of zero columns and zero rows.

Usage

From source file:search2go.UIFrame.java

public void identify(boolean fullProcess) {
    if ("Stop".equals(btnGTermIdent.getText())) {
        identButton.activate();/*from w ww .ja va  2s.  c  o m*/
        try {
            if (os.isWindows()) {
                Runtime.getRuntime().exec("cmd /C TaskKill -IM blastx.exe -F");
                Runtime.getRuntime().exec("cmd /C TaskKill -IM blastn.exe -F");
                Runtime.getRuntime().exec("cmd /C TaskKill -IM blastp.exe -F");
            } else {
                Runtime.getRuntime().exec("killAll -KILL blastx");
                Runtime.getRuntime().exec("killAll -KILL blastn");
                Runtime.getRuntime().exec("killAll -KILL blastp");
            }
        } catch (IOException ex) {
            System.out.println("Error closing child processes");
        }
        prgIdentification.setIndeterminate(false);
    } else if (currentProj.checkStage(2)) {
        if (currentProj.isAvaialable()) {
            pnlChartHolder.removeAll();
            lstQueries.clearSelection();
            lstQueries.setModel(new DefaultListModel());
            txtTermInfo.setText("");

            tblGOFreq.clearSelection();
            DefaultTableModel d = new DefaultTableModel();
            d.setColumnCount(2);
            d.setColumnIdentifiers(new String[] { "GO ID", "Frequency" });
            tblGOFreq.setModel(d);

            identSequences = new ArrayList<>();

            resetIdentCount();
            for (int i = 0; i < 3; i++) {
                if (currentProj.getTargetDBString().contains(targetDBs[i])) {
                    JTextArea tempHolder = new JTextArea();
                    ProcessSequence identSequence = new ProcessSequence(currentProj,
                            new ProcessSequenceFiller(tempHolder, Integer.toString(i)) {
                                private final JTextArea sequenceOutput = tempHolder;

                                @Override
                                public void run() {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            for (String record : sequenceOutput.getText().split("\n")) {
                                                String name = record.split("\t")[0];
                                                GTerm nextGTerm = new GTerm(
                                                        name.substring(0, name.indexOf("[")),
                                                        name.substring(name.indexOf("[")));
                                                nextGTerm.setTopLevel(topLevels[Integer.parseInt(getNotes())]);
                                                nextGTerm.setFrequency(Integer.parseInt(record.split("\t")[1]));
                                                gTerms.addGTerm(nextGTerm);
                                            }
                                            incIdentCount();
                                        }
                                    }).start();
                                }
                            });
                    identSequences.add(identSequence);
                    Process checkFullIdent = new Process(tempHolder);
                    Path checkFullIdentPath = new Path("Processes");
                    checkFullIdentPath.append("gotFullGTerms.py");
                    checkFullIdent.setScriptCommand(checkFullIdentPath.toEscString());
                    checkFullIdent.addParameter("dir", currentProj.getPath().toEscString());
                    checkFullIdent.addParameter("db", targetDBs[i]);
                    identSequence.addProcess(checkFullIdent);
                    ProcessSequenceFiller doFullCheckOutputGetter = new ProcessSequenceFiller(tempHolder,
                            targetDBs[i]) {
                        @Override
                        public void run() {
                            if (this.getOutBox().getText().contains("false")) {
                                this.getOutBox().setText("");
                                Process mapSequenceGO = new Process(this.getOutBox());
                                Path mapSequenceGOPath = new Path("Processes");
                                mapSequenceGOPath.append("mapSequenceGO.py");
                                mapSequenceGO.setScriptCommand(mapSequenceGOPath.toEscString());
                                mapSequenceGO.addParameter("dir", currentProj.getPath().toEscString());
                                mapSequenceGO.addParameter("db", this.getNotes());
                                this.getParentSequence(0).addProcess(mapSequenceGO);

                                Process parseConverts = new Process(this.getOutBox());
                                Path parseConvertsPath = new Path("Processes");
                                parseConvertsPath.append("parseConvertedIDs.py");
                                parseConverts.setScriptCommand(parseConvertsPath.toEscString());
                                parseConverts.addParameter("dir", currentProj.getPath().toEscString());
                                parseConverts.addParameter("db", this.getNotes());
                                this.getParentSequence(0).addProcess(parseConverts);

                                identSequence.addProcess(new ProcessSequenceFiller(tempHolder) {
                                    @Override
                                    public void run() {
                                        tempHolder.setText("");
                                        try {
                                            this.finish();
                                        } catch (IOException ex) {
                                            System.out.println("Error finishing identification process filler");
                                        }
                                    }

                                });
                            }
                            this.getOutBox().setText("");
                            Process getMatchedQueryFreq = new Process(this.getOutBox());
                            Path getMatchedQueryFreqPath = new Path("Processes");
                            getMatchedQueryFreqPath.append("getMatchedQueryFreq.py");
                            getMatchedQueryFreq.setScriptCommand(getMatchedQueryFreqPath.toEscString());
                            getMatchedQueryFreq.addParameter("dir", currentProj.getPath().toEscString());
                            getMatchedQueryFreq.addParameter("db", this.getNotes());
                            this.getParentSequence(0).addProcess(getMatchedQueryFreq);
                            try {
                                this.finish();
                            } catch (IOException ex) {
                                System.out.println("Error finishing identification process filler");
                            }
                        }
                    };

                    identSequence.addProcess(doFullCheckOutputGetter);
                    try {
                        gTerms.getGTerms().clear();
                        identSequence.start();
                        identButton.setStopTargets(
                                identSequences.toArray(new ProcessSequence[identSequences.size()]));
                        if (currentProj.willDoCC())
                            currentProj.setStage(0, 2);
                        if (currentProj.willDoBP())
                            currentProj.setStage(1, 2);
                        if (currentProj.willDoBP())
                            currentProj.setStage(2, 2);
                        prgIdentification.setIndeterminate(true);
                    } catch (IOException ex) {
                        Logger.getLogger(UIFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            identButton.activate();
        } else
            javax.swing.JOptionPane.showMessageDialog(this,
                    "Another function is currently being performed on this project, please wait until completion or manually stop the process.");
    } else {
        System.out.println(currentProj.getStage());
        javax.swing.JOptionPane.showMessageDialog(this,
                "Mapping data unavailable. Please complete mapping step or switch to a project with completed mapping to continue.");
    }

}

From source file:search2go.UIFrame.java

private void fillIdentTable(GTermSet terms, boolean identStage) {
    terms.stringFilter();/*  w w w  .  j av a2 s  .  com*/
    GTermTableModel = new DefaultTableModel();
    GTermTableModel.setColumnCount(2);
    GTermTableModel.setColumnIdentifiers(new String[] { "GO ID", "Frequency" });
    tblGOFreq.setModel(GTermTableModel);
    terms.freqSort();
    for (GTerm term : terms.getGTerms()) {
        String[] row = { term.getID() + term.getName(), term.getFrequencyObject().toString() };
        GTermTableModel.addRow(row);
    }
    tblGOFreq.setModel(GTermTableModel);
    if (identStage) {
        prgIdentification.setIndeterminate(false);
        prgFullProcess.setIndeterminate(false);
        txtFullOutput.append(
                "Done identifying!\nPlease go to the 'Identification' tab to see the results or 'Analysis' to view related graphs.\n");
        if (currentProj.willDoCC())
            currentProj.setStage(0, 3);
        if (currentProj.willDoBP())
            currentProj.setStage(1, 3);
        if (currentProj.willDoBP())
            currentProj.setStage(2, 3);
        identButton.restore();
        fullButton.restore();
        currentProj.setAvailable(true);
    }
}

From source file:interfaces.InterfazPrincipal.java

private void botonBuscarClienteCrearFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarClienteCrearFacturaActionPerformed

    String nombre = nombreClienteCrearFactura.getText();
    String identificacion = IdentificacionClienteBuscarFactura.getText();

    ControladorCliente controladorCliente = new ControladorCliente();

    try {/*from   www  . j av  a 2s. com*/
        int id = 0;
        if (!identificacion.equals("")) {
            id = Integer.parseInt(identificacion);
        }

        ArrayList<Cliente> listaClientes = controladorCliente.obtenerClientes(nombre, id);

        if (listaClientes.isEmpty()) {
            mensajesBusquedaClientesFactura.setText("La busqueda no arrojo resultados");
            return;
        }

        final JDialog dialogoEditar = new JDialog(this);
        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(600, 310);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

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

        JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 4;
        c.insets = new Insets(15, 200, 40, 0);
        c.ipadx = 100;
        Font textoGrande = new Font("Arial", 1, 18);
        editarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(editarTextoPrincipalDialogo, c);

        /*Vector col = new Vector();
         col.add("1");
         col.add("2");
         col.add("3");
         col.add("4");
         Vector row = new Vector();
                
         for (int i = 0; i < listaClientes.size(); i++) {
         Cliente cliente = listaClientes.get(i);
         Vector temp = new Vector();
         temp.add((i + 1) + "");
         temp.add(cliente.getNombre());
         temp.add(cliente.getCliente_id() + "");
         temp.add(cliente.getMonto_prestamo() + "");
         System.out.println("info" + cliente.getNombre() + "," + cliente.getMonto_prestamo());
         row.add(temp);
         }
                
         final JTable table = new JTable(row, col);         */
        final JTable table = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

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

        modeloTabla.addColumn("Numero");
        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");
        modeloTabla.addColumn("Monto Prestamo");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2", "3", "4" };
            data[0] = (i + 1);
            data[1] = listaClientes.get(i).getCliente_id();
            data[2] = listaClientes.get(i).getNombre();
            data[3] = listaClientes.get(i).getMonto_prestamo();

            modeloTabla.addRow(data);
        }

        table.setModel(modeloTabla);
        table.getColumn("Numero").setMinWidth(50);
        table.getColumn("Identificacin").setMinWidth(50);
        table.getColumn("Nombre").setMinWidth(110);
        table.getColumn("Monto Prestamo").setMinWidth(110);

        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setPreferredSize(new Dimension(320, 150));

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                String identificacion = table.getValueAt(table.getSelectedRow(), 3).toString();
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //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(identificacion)
                                + " 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] };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                }
                nombreClienteCrearFactura.setText(table.getValueAt(table.getSelectedRow(), 2).toString());
                IdentificacionClienteBuscarFactura
                        .setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                double montoPrestamo = Double
                        .parseDouble(table.getValueAt(table.getSelectedRow(), 3).toString());
                Double totalDisponible = montoPrestamo - pago;
                valorActualPrestamo.setText(String.valueOf(totalDisponible));
                //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
                botonAgregarProducto.setEnabled(true);
                botonGuardarFactura.setEnabled(true);
                botonEstablecerMontoFactura.setEnabled(true);
                dialogoEditar.dispose();
            }
        });

        c.insets = new Insets(0, 5, 10, 0);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 1;
        c.ipadx = 200;

        //panelDialogo.add(table, c);
        panelDialogo.add(scroll, c);
        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);
    } catch (Exception e) {
        mensajesBusquedaClientesFactura.setText("La identificacion debe ser un numero");

    }

}

From source file:interfaces.InterfazPrincipal.java

private void botonAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarProductoActionPerformed
    String nombre = jTextField_Factura_Producto_Nombre.getText();
    String descripcion = jTextField_Factura_Producto_Descripcion.getText();
    ControladorProducto controladorPro = new ControladorProducto();
    String restriccion = "";

    boolean encounter = true;

    if (!nombre.equals("")) {
        if (encounter) {
            encounter = false;/*from  w w w. ja va  2  s .c  o  m*/
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " nombre like '%" + nombre + "%'";
    }

    if (!descripcion.equals("")) {
        if (encounter) {
            encounter = false;
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " descripcion like '%" + descripcion + "%'";
    }

    ArrayList<Productos> listaDeProductos = controladorPro.getProducto(restriccion);

    final JDialog dialogoEditar = new JDialog(this);
    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(600, 310);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

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

    JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Producto");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 6;
    c.insets = new Insets(15, 200, 40, 0);
    c.ipadx = 100;
    Font textoGrande = new Font("Arial", 1, 18);
    editarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(editarTextoPrincipalDialogo, c);

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

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

    modeloTabla.addColumn("Numero");
    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");
    modeloTabla.addColumn("Descripcion");
    modeloTabla.addColumn("Unidades Disponibles");
    modeloTabla.addColumn("Precio");

    //LLenar tabla
    for (int i = 0; i < listaDeProductos.size(); i++) {
        Object[] data = { "1", "2", "3", "4", "5", "6" };
        data[0] = (i + 1);
        data[1] = listaDeProductos.get(i).getProductoId();
        data[2] = listaDeProductos.get(i).getNombre();
        data[3] = listaDeProductos.get(i).getDescripcion();
        data[4] = listaDeProductos.get(i).getUnidadesDisponibles();
        data[5] = listaDeProductos.get(i).getPrecio();

        modeloTabla.addRow(data);
    }

    table.setModel(modeloTabla);
    table.getColumn("Numero").setMinWidth(50);
    table.getColumn("Identificacin").setMinWidth(50);
    table.getColumn("Nombre").setMinWidth(110);
    table.getColumn("Descripcion").setMinWidth(110);
    table.getColumn("Unidades Disponibles").setMinWidth(40);
    table.getColumn("Precio").setMinWidth(110);

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize(new Dimension(320, 150));

    //final JTable table = new JTable(row, col);       
    table.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            //jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
            //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
            DefaultTableModel modelo = (DefaultTableModel) TablaDeFacturaProducto.getModel();

            Object[] fila = new Object[7];

            fila[0] = table.getValueAt(table.getSelectedRow(), 0).toString();
            fila[1] = table.getValueAt(table.getSelectedRow(), 1).toString();
            fila[2] = table.getValueAt(table.getSelectedRow(), 2).toString();
            fila[3] = table.getValueAt(table.getSelectedRow(), 3).toString();
            //fila[4] = table.getValueAt(table.getSelectedRow(), 4).toString();
            fila[4] = (String) JOptionPane.showInputDialog("Ingrese el nmero de unidades que va a vender");
            fila[5] = table.getValueAt(table.getSelectedRow(), 5).toString();

            Double valorProducto = Double.parseDouble((String) fila[5]);
            String valorActualProducto = String.valueOf(Double.parseDouble(valorActualFactura.getText())
                    + Double.parseDouble((String) fila[4]) * valorProducto);
            valorActualFactura.setText(valorActualProducto);
            fila[6] = Double.parseDouble((String) fila[4]) * valorProducto;
            modelo.addRow(fila);
            //modelo.getColumnName(4).
            /*TablaDeFacturaProducto.setModel(modelo);
             TablaDeFacturaProducto.getColumnClass(4). ;*/
            dialogoEditar.dispose();
        }
    });

    c.insets = new Insets(0, 5, 10, 0);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 200;

    panelDialogo.add(scroll, c);

    //panelDialogo.add(table, c);
    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

}

From source file:interfaces.InterfazPrincipal.java

private void BotonBuscarClienteSaldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonBuscarClienteSaldoActionPerformed
    String nombreCliente = nombreClienteBusquedaSaldo.getText();
    //08-11-2014 listar clientes por nombre
    ControladorCliente controladorCliente = new ControladorCliente();
    ArrayList<Cliente> listaClientes = new ArrayList<>();

    if (nombreCliente.equals("")) {
        listaClientes = controladorCliente.obtenerClientes();
    } else {/*  w  ww  .j a v a2  s.  co m*/
        listaClientes = controladorCliente.obtenerClientes(nombreCliente, 0);
    }

    //08-11-2014 Crear dialogo de bsqueda
    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(300, 300);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

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

    JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;
    c.insets = new Insets(10, 60, 10, 10);
    Font textoGrande = new Font("Arial", 1, 16);
    ediitarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(ediitarTextoPrincipalDialogo, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 2;
    c.insets = new Insets(10, 10, 10, 10);
    final JTable tablaDialogo = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

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

    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");

    //LLenar tabla
    for (int i = 0; i < listaClientes.size(); i++) {
        Object[] data = { "1", "2" };
        data[0] = listaClientes.get(i).getCliente_id();
        data[1] = listaClientes.get(i).getNombre();
        modeloTabla.addRow(data);
    }

    tablaDialogo.setModel(modeloTabla);
    tablaDialogo.getColumn("Identificacin").setMinWidth(110);
    tablaDialogo.getColumn("Nombre").setMinWidth(110);
    tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(tablaDialogo);
    scroll.setPreferredSize(new Dimension(220, 150));

    panelDialogo.add(scroll, c);

    c.insets = new Insets(0, 0, 0, 10);
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonGuardarClienteDialogo = new JButton("Elegir");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

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

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = tablaDialogo.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

            } else {
                Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                mostrarIdentificacionCliente.setText(String.valueOf(identificacionCliente));
                String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 1));

                //Limitar a 15 caracteres
                if (nombreClientePago.length() >= 15) {
                    nombreClientePago = nombreClientePago.substring(0, 12);

                }
                textoPersonaSaldo.setText(nombreClientePago);

                DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoClientes.getModel();
                for (int i = 0; i < modeloClientes.getRowCount(); i++) {
                    modeloClientes.removeRow(i);
                }

                modeloClientes.setRowCount(0);
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //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);

                    TablaDeSaldoClientes.setModel(modeloClientes);
                    NumberFormat formatter = new DecimalFormat("#0");

                    String valorMovimiento = String.valueOf(formatter.format(Double.parseDouble(datos[4])));
                    Object[] rowData = { datos[1], datos[2], datos[3], valorMovimiento };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                    modeloClientes.addRow(rowData);
                }

                TablaDeSaldoClientes.setModel(modeloClientes);
                NumberFormat formatter = new DecimalFormat("#0");
                textoTotalDebe.setText(String.valueOf(formatter.format(pago)));
                dialogoEditar.dispose();

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

        }
    });
}

From source file:interfaces.InterfazPrincipal.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    String nombreCliente = nombreClienteReporteCliente.getText();
    String identificacion = identificacionClienteCliente.getText();
    try {/*from   w  w  w. java 2s  .  com*/
        //08-11-2014 listar clientes por nombre
        ControladorCliente controladorCliente = new ControladorCliente();
        ArrayList<Cliente> listaClientes = new ArrayList<Cliente>();

        if (nombreCliente.equals("") && identificacion.equals("")) {
            listaClientes = controladorCliente.obtenerClientes();
        } else {
            int identificacionNumerico = 0;
            if (!identificacion.equals("")) {
                identificacionNumerico = Integer.parseInt(identificacion);
            }
            listaClientes = controladorCliente.obtenerClientes(nombreCliente, identificacionNumerico);
        }

        //08-11-2014 Crear dialogo de bsqueda
        final JDialog dialogoEditar = new JDialog(this);

        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(300, 300);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

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

        JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(10, 60, 10, 10);
        Font textoGrande = new Font("Arial", 1, 16);
        ediitarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(ediitarTextoPrincipalDialogo, c);

        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        c.insets = new Insets(10, 10, 10, 10);
        final JTable tablaDialogo = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

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

        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2" };
            data[0] = listaClientes.get(i).getCliente_id();
            data[1] = listaClientes.get(i).getNombre();
            modeloTabla.addRow(data);
        }

        tablaDialogo.setModel(modeloTabla);
        tablaDialogo.getColumn("Identificacin").setMinWidth(110);
        tablaDialogo.getColumn("Nombre").setMinWidth(110);
        tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(tablaDialogo);
        scroll.setPreferredSize(new Dimension(220, 150));

        panelDialogo.add(scroll, c);

        c.insets = new Insets(0, 0, 0, 10);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonGuardarClienteDialogo = new JButton("Elegir");
        panelDialogo.add(botonGuardarClienteDialogo, c);

        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonCerrarClienteDialogo = new JButton("Cancelar");
        panelDialogo.add(botonCerrarClienteDialogo, c);

        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);

        botonCerrarClienteDialogo.addActionListener(new ActionListener() {

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

        botonGuardarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int row = tablaDialogo.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

                } else {
                    Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                    jTextFieldIdentificacionClienteReporte.setText(String.valueOf(identificacionCliente));
                    botonGenerarReporteCliente.setEnabled(true);
                    dialogoEditar.dispose();

                }

            }
        }); // TODO add your handling code here:     
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "El valor de la identificacin de ser numrico");

    }

}

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 v  a2  s .com
        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:interfaces.InterfazPrincipal.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    // TODO add your handling code here:
    String nombre = jTextFieldNombreSaldoProveedores.getText();
    ControladorProveedores controladorProveedores = new ControladorProveedores();
    ArrayList<Proveedores> listaProveedores = controladorProveedores.obtenerProveedores("", nombre);

    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Buscar proveedores");
    dialogoEditar.setSize(500, 300);/*from   w w  w  . jav a2s.  c o  m*/
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

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

    JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar Proveedores");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 3;
    c.insets = new Insets(10, 60, 10, 10);
    Font textoGrande = new Font("Arial", 1, 16);
    ediitarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(ediitarTextoPrincipalDialogo, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 3;
    c.insets = new Insets(10, 10, 10, 10);
    final JTable tablaDialogo = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    ;
    modeloTabla.addColumn("ID");
    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");

    //LLenar tabla
    for (int i = 0; i < listaProveedores.size(); i++) {
        Object[] data = { "1", "2", "3" };
        data[0] = listaProveedores.get(i).getID();
        data[1] = listaProveedores.get(i).getIdentificacion();
        data[2] = listaProveedores.get(i).getNombre();
        System.out.println("Nombre!!" + data[2]);
        modeloTabla.addRow(data);
    }

    tablaDialogo.setModel(modeloTabla);
    tablaDialogo.getColumn("ID").setMinWidth(70);
    tablaDialogo.getColumn("Identificacin").setMinWidth(60);
    tablaDialogo.getColumn("Nombre").setMinWidth(150);
    tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(tablaDialogo);
    scroll.setPreferredSize(new Dimension(220, 150));

    panelDialogo.add(scroll, c);

    c.insets = new Insets(0, 0, 0, 10);
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonGuardarClienteDialogo = new JButton("Elegir");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

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

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = tablaDialogo.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

            } else {
                Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                Object idCliente = tablaDialogo.getValueAt(row, 1);
                mostrarIDProveedor.setText(String.valueOf(identificacionCliente));
                String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 2));

                //Limitar a 15 caracteres
                if (nombreClientePago.length() >= 15) {
                    nombreClientePago = nombreClientePago.substring(0, 12);

                }
                textoNombreProveedor.setText(nombreClientePago);

                DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoProveedor.getModel();
                for (int i = 0; i < modeloClientes.getRowCount(); i++) {
                    modeloClientes.removeRow(i);
                }

                modeloClientes.setRowCount(0);
                ControladorFlujoCompras controladorFlujoCompra = new ControladorFlujoCompras();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<Flujo_Compra> flujosProveedor = controladorFlujoCompra.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));
                dialogoEditar.dispose();

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

        }

    });

}

From source file:app.RunApp.java

/**
 * Set label IR// www  . jav a2s. co  m
 * 
 * @param jtable Table
 * @param stat Statistics
 * @param cp CategoryPlot
 * @return Generated TableModel
 * @throws Exception 
 */
private TableModel irLabelsetsTableModel(JTable jtable, Statistics stat, CategoryPlot cp) throws Exception {
    DefaultTableModel tableModel = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            //This causes all cells to be not editable
            return false;
        }
    };

    DefaultCategoryDataset myData = new DefaultCategoryDataset();

    tableModel.addColumn("Labelset id");
    tableModel.addColumn("IR values");

    //Labelsets frequency
    HashMap<LabelSet, Integer> labelsetsFrequency = stat.labelCombCount();
    labelsetStringByIR = new ArrayList<>(labelsetsFrequency.size());

    Set<LabelSet> keysets = labelsetsFrequency.keySet();

    Object[] row = new Object[2];

    int count = 1;
    double IR_labelset;
    int max = getMax(keysets, labelsetsFrequency);

    ArrayList<ImbalancedFeature> listImbalanced = new ArrayList();
    ImbalancedFeature temp;

    int value;

    for (LabelSet current : keysets) {
        value = labelsetsFrequency.get(current);
        IR_labelset = max / (value * 1.0);
        String temp1 = MetricUtils.truncateValue(IR_labelset, 4);
        IR_labelset = Double.parseDouble(temp1);

        temp = new ImbalancedFeature(current.toString(), value, IR_labelset);
        listImbalanced.add(temp);
    }

    labelsetsIRSorted = new ImbalancedFeature[listImbalanced.size()];
    labelsetsByIR = new double[listImbalanced.size()]; //stores IR per labelset

    String truncate;

    while (!listImbalanced.isEmpty()) {
        temp = Utils.getMin(listImbalanced);

        labelsetsIRSorted[count - 1] = temp;
        labelsetsByIR[count - 1] = temp.getIRIntraClass();

        row[0] = count;

        truncate = Double.toString(temp.getIRIntraClass());
        row[1] = MetricUtils.getValueFormatted(truncate, 3);

        tableModel.addRow(row);

        myData.setValue(temp.getIRIntraClass(), Integer.toString(count), "");
        labelsetStringByIR.add(temp.getName());

        count++;
        listImbalanced.remove(temp);
    }

    jtable.setModel(tableModel);
    jtable.setBounds(jtable.getBounds());

    //Resize columns
    TableColumnModel tcm = jtable.getColumnModel();

    tcm.getColumn(0).setPreferredWidth(50);
    tcm.getColumn(1).setPreferredWidth(50);

    //graph
    cp.setDataset(myData);

    //get mean
    double sum = 0;
    for (int i = 0; i < labelsetsIRSorted.length; i++) {
        sum += labelsetsIRSorted[i].getIRIntraClass();
    }
    sum = sum / labelsetsIRSorted.length;

    Marker start = new ValueMarker(sum);
    start.setPaint(Color.blue);
    start.setLabelFont(new Font("SansSerif", Font.BOLD, 12));
    start.setLabel("                        Mean: " + MetricUtils.truncateValue(sum, 4));
    cp.addRangeMarker(start);

    return jtable.getModel();
}

From source file:app.RunApp.java

/**
 * Set frequency of labelsets/*from  ww  w  .  ja v a 2s .  c  o  m*/
 * 
 * @param jtable Table
 * @param dataset Dataset
 * @param stat Statistics
 * @param cp Plot
 * @return Generated TableModel
 * @throws Exception 
 */
private TableModel labelsetsFrequencyTableModel(JTable jtable, MultiLabelInstances dataset, Statistics stat,
        CategoryPlot cp) throws Exception {
    DefaultTableModel tableModel = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            //This causes all cells to be not editable
            return false;
        }
    };

    DefaultCategoryDataset myData = new DefaultCategoryDataset();

    tableModel.addColumn("Labelset Id");
    tableModel.addColumn("# Examples");
    tableModel.addColumn("Frequency");

    double freq;

    //Labelsets frequency
    HashMap<LabelSet, Integer> result = stat.labelCombCount();
    labelsetStringsByFreq = new ArrayList<>(result.size());

    double sum = 0.0;
    Set<LabelSet> keysets = result.keySet();

    Object[] row = new Object[3];

    int count = 1;

    ArrayList<ImbalancedFeature> listImbalanced = new ArrayList();
    ImbalancedFeature temp;

    int value;
    for (LabelSet current : keysets) {
        value = result.get(current);
        temp = new ImbalancedFeature(current.toString(), value);
        listImbalanced.add(temp);
    }

    labelsetsSorted = new ImbalancedFeature[listImbalanced.size()];
    labelsetsFrequency = new double[listImbalanced.size()];

    while (!listImbalanced.isEmpty()) {
        temp = Utils.getMax(listImbalanced);
        labelsetsSorted[count - 1] = temp;
        value = temp.getAppearances();
        labelsetsFrequency[count - 1] = value;
        row[0] = count;
        freq = value * 1.0 / dataset.getNumInstances();
        sum += freq;

        String valueFreq = Double.toString(freq);
        row[1] = value;

        row[2] = MetricUtils.getValueFormatted(valueFreq, 4);
        tableModel.addRow(row);

        String id = "ID: " + Integer.toString(count);

        myData.setValue(freq, id, "");
        labelsetStringsByFreq.add(temp.getName());

        count++;
        listImbalanced.remove(temp);
    }

    jtable.setModel(tableModel);
    jtable.setBounds(jtable.getBounds());

    TableColumnModel tcm = jtable.getColumnModel();
    tcm.getColumn(0).setPreferredWidth(50);
    tcm.getColumn(1).setPreferredWidth(50);
    tcm.getColumn(2).setPreferredWidth(60);

    //graph
    cp.setDataset(myData);

    sum = sum / keysets.size();
    Marker start = new ValueMarker(sum);
    start.setLabelFont(new Font("SansSerif", Font.BOLD, 12));
    start.setLabel("                        Mean: " + MetricUtils.truncateValue(sum, 4));
    start.setPaint(Color.red);
    cp.addRangeMarker(start);

    return jtable.getModel();
}