Example usage for javax.swing.table DefaultTableModel getRowCount

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

Introduction

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

Prototype

public int getRowCount() 

Source Link

Document

Returns the number of rows in this data table.

Usage

From source file:interfaces.InterfazPrincipal.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    String factura_id = jTextField_BuscarFactura_ID.getText();
    String cliente_id = jTextField_BuscarFactura_Cliente.getText();
    ControladorFactura controladorFactura = new ControladorFactura();
    String restriccion = "";
    if (!factura_id.equals("")) {
        restriccion += " where factura_id like '%" + factura_id + "%'";
        if (!cliente_id.equals("")) {
            restriccion += " or cliente_id like '%" + cliente_id + "%'";
        }//from   www .  j  a  va2 s  .c  o m
    } else {
        if (!cliente_id.equals("")) {
            restriccion += " where cliente_id like '%" + cliente_id + "%'";
        }
    }

    //String restriccion2 = " where factura_id like '%"+factura_id+"%' or cliente_id like '%"+cliente_id+"%'";
    ArrayList<Factura> listaFactura = controladorFactura.getFactura(restriccion);

    DefaultTableModel modelo = (DefaultTableModel) TablaDeBuscarFactura.getModel();

    for (int i = 0; i < modelo.getRowCount(); i++) {
        modelo.removeRow(i);
    }
    modelo.setRowCount(0);
    ControladorCliente controladorCliente = new ControladorCliente();
    for (int i = 0; i < listaFactura.size(); i++) {
        Factura factura = listaFactura.get(i);
        Object[] fila = new Object[6];
        fila[0] = (i + 1);
        fila[1] = factura.getFactura_id();
        fila[2] = factura.getFecha();

        Cliente cliente = controladorCliente.obtenerClientePorID(factura.getCliente_id());
        fila[3] = cliente.getNombre();
        fila[4] = factura.getEstado();

        Double valorFactura = factura.getValor();
        NumberFormat formatter = new DecimalFormat("#0");

        fila[5] = formatter.format(valorFactura);
        //button.setText("<HTML>Click the <FONT color=\"#000099\"><U>link "+i+"</U></FONT>"+ " to go to the Java website.</HTML>");
        modelo.addRow(fila);

    }

    TablaDeBuscarFactura.setModel(modelo);
}

From source file:interfaces.InterfazPrincipal.java

private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
    // TODO add your handling code here:
    String NitProveedor = campoNitBuscarProveedor.getText();
    String buscarNombreProveedor = campoNombreBuscarProveedor.getText();

    String restriccion = " where IDProveedor in ( select ID from Proveedores where 1";

    if (!NitProveedor.equals("")) {
        restriccion += " and ID = " + NitProveedor;
    }//from   w  w  w  .  jav a2  s  .  c o m

    if (!buscarNombreProveedor.equals("")) {
        restriccion += " and nombre LIKE '\"%" + buscarNombreProveedor + "%\"";
    }

    restriccion += ")";
    ControladorCompraProveedor controladorCompraProveedor = new ControladorCompraProveedor();
    ArrayList<CompraProveedores> listaCompraProveedores = controladorCompraProveedor
            .obtenerCompraProveedoresPorRestriccion(restriccion);

    DefaultTableModel modeloTabla = (DefaultTableModel) tablaMostrarCompras.getModel();

    for (int i = 0; i < modeloTabla.getRowCount(); i++) {
        modeloTabla.removeRow(i);
    }
    modeloTabla.setRowCount(0);

    for (int i = 0; i < listaCompraProveedores.size(); i++) {
        CompraProveedores compraProveedores = listaCompraProveedores.get(i);
        Object[] fila = new Object[4];
        //numero, proveedor, fecha, valor
        fila[0] = compraProveedores.getID();

        ControladorProveedores controladorProveedores = new ControladorProveedores();
        Proveedores proveedores = controladorProveedores
                .obtenerProveedores(String.valueOf(compraProveedores.getIDProveedor()), "").get(0);
        fila[1] = proveedores.getNombre();
        fila[2] = compraProveedores.getFecha();
        fila[3] = compraProveedores.getMontoCompra();

        modeloTabla.addRow(fila);

    }
    tablaMostrarCompras.setModel(modeloTabla);
}

From source file:interfaces.InterfazPrincipal.java

private void botonEstablecerMontoFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonEstablecerMontoFacturaActionPerformed
    // TODO add your handling code here:
    int seleccion = JOptionPane.showConfirmDialog(this,
            "Al establecer un monto de factura, no se considerarn los productos en ella \n Desea continuar?",
            "Mensaje del sistema", JOptionPane.YES_NO_OPTION);
    if (seleccion == 0) {

        try {/*from   ww w.  j av  a2 s .  c o m*/
            double monto = Double.parseDouble(valorMontoFactura.getText());

            if (monto <= 0.0) {
                throw new Exception();

            }
            valorActualFactura.setText(valorMontoFactura.getText());

            DefaultTableModel modeloTabla = (DefaultTableModel) TablaDeFacturaProducto.getModel();

            //Borrar filas
            for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                modeloTabla.removeRow(i);
            }
            modeloTabla.setRowCount(0);

            TablaDeFacturaProducto.setModel(modeloTabla);
            botonAgregarProducto.setEnabled(false);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "El valor debe ser numrico positivo", "Advertencia",
                    JOptionPane.WARNING_MESSAGE);
        }

    }

}

From source file:interfaces.InterfazPrincipal.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    String nombre = jTextField_Producto_Con_Nombre.getText();
    String descripcion = jTextField_Producto_Con_Descripcion.getText();
    String unidades_string = jTextField_Producto_Con_Unidades.getText();
    String precio_string = jTextField4.getText();

    int unidades = 0;
    double precio = 0;
    try {/*  ww  w  .  ja  va  2  s .  c o  m*/
        if (!unidades_string.equals("")) {
            unidades = Integer.parseInt(unidades_string);
        }
        if (!precio_string.equals("")) {
            precio = Double.parseDouble(precio_string);
        }

        ControladorProducto controladorPro = new ControladorProducto();
        String restriccion = "";

        boolean encounter = true;

        if (!nombre.equals("")) {
            if (encounter) {
                encounter = false;
                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 + "%'";
        }

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

            restriccion += " unidades =" + unidades;
        }

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

            restriccion += " precio =" + precio;
        }

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

        //Agregar filas
        DefaultTableModel modelo = (DefaultTableModel) TablaDeProductos.getModel();

        if (modelo.getRowCount() > 0) {
            for (int i = modelo.getRowCount() - 1; i > -1; i--) {
                modelo.removeRow(i);
            }
        }

        for (int i = 0; i < listaDeProductos.size(); i++) {
            Productos producto = listaDeProductos.get(i);
            Object[] fila = new Object[7];
            fila[0] = (i + 1);
            fila[1] = producto.getProductoId();
            fila[2] = producto.getNombre();
            fila[3] = producto.getDescripcion();
            fila[4] = producto.getUnidadesDisponibles();
            fila[5] = producto.getPrecio();
            fila[6] = producto.getCodigoBarras();
            modelo.addRow(fila);

        }

        TablaDeProductos.setModel(modelo);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this,
                "Error al consultar los productos\nInformacin tcnica\n" + e.toString(), "Error",
                JOptionPane.ERROR_MESSAGE);
    }

}

From source file:interfaces.InterfazPrincipal.java

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
    ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
    ArrayList<String[]> listado = controladorFlujoFactura.getTodosFlujo_Factura("");
    DefaultTableModel modelo = (DefaultTableModel) TablaDeReporteDiario.getModel();

    if (modelo.getRowCount() > 0) {
        for (int k = modelo.getRowCount() - 1; k > -1; k--) {
            modelo.removeRow(k);/*w w w .j a  v  a2s  .  com*/
        }
    }
    int contador = 1;
    double abono = 0;
    double deuda = 0;
    for (int i = 0; i < listado.size(); i++) {
        String[] fila = listado.get(i);

        String[] partirEspacios = fila[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]);
        Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta);

        int anioInicial = fechaReporteDiario.getSelectedDate().get(Calendar.YEAR);
        int mesInicial = fechaReporteDiario.getSelectedDate().get(Calendar.MONTH) + 1;
        int diaInicial = fechaReporteDiario.getSelectedDate().get(Calendar.DAY_OF_MONTH);
        Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial);

        //fechaReporteDiarioHasta
        int anioFinal = fechaReporteDiarioHasta.getSelectedDate().get(Calendar.YEAR);
        int mesFinal = fechaReporteDiarioHasta.getSelectedDate().get(Calendar.MONTH) + 1;
        int diaFinal = fechaReporteDiarioHasta.getSelectedDate().get(Calendar.DAY_OF_MONTH);
        Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal);

        //System.out.println("antes");
        //System.out.println("Va a comparar" + fechaDeLaBD.toString());
        //System.out.println(" con " + fechaInicialRango.toString());
        if (fechaDeLaBD.compareTo(fechaInicialRango) >= 0 && fechaDeLaBD.compareTo(fechaFinalRango) <= 0) {
            //System.out.println("Entra");
            Object[] row = new Object[5];
            row[0] = (contador);
            contador++;
            row[1] = fila[1];
            row[2] = fila[3];
            row[3] = fila[2];
            row[4] = fila[4];
            modelo.addRow(row);
            //flujo_id","factura_id","tipo_flujo","fecha","valor"
            /*System.out.println("fila 0" + fila[0]);
             System.out.println("fila 1" + fila[1]);
             System.out.println("fila 2" + fila[2]);
             System.out.println("fila 3" + fila[3]);*/
            if (fila[2].equals("abono")) {
                abono += Double.parseDouble(fila[4]);
            } else {
                deuda += Double.parseDouble(fila[4]);
            }
            ;
        }

    }
    ReporteDiarioAbono.setText(abono + "");
    ReporteDiarioDeuda.setText(deuda + "");
    TablaDeReporteDiario.setModel(modelo);
    Object opciones[] = { "Cerrar", "Imprimir", "Guardar en disco" };
    int opcion = JOptionPane.showOptionDialog(this, "Se ha generado el diario solicitado\nQue desea hacer?",
            "Elija una opcin", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opciones,
            null);
    GenerarReporteDiario generarReporteDiario = new GenerarReporteDiario();
    switch (opcion) {
    case 1:
        generarReporteDiario.imprimiDiario(fechaReporteDiario.getSelectedDate(),
                fechaReporteDiarioHasta.getSelectedDate(), modelo, this);
        break;
    case 2:
        PDDocument documento = generarReporteDiario.crearDiario(fechaReporteDiario.getSelectedDate(),
                fechaReporteDiarioHasta.getSelectedDate(), modelo, this);
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivo PDF", "pdf", "text");
        fc.setFileFilter(filter);
        fc.showSaveDialog(this);
        if (fc.getSelectedFile() != null) {
            File selectedFile = fc.getSelectedFile();
            try {

                documento.save(selectedFile + ".pdf");
                JOptionPane.showMessageDialog(this, "El archivo ha sido guardado en disco");

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "EL Archivo no se puede leer!");
            }
        }
        break;

    default:
        break;
    }
}

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  ww  .j av a  2 s  .  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: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 w w.  j  a v  a  2  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 botonGuardarFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGuardarFacturaActionPerformed
    // TODO add your handling code here:

    String id_cliente = jTextField_Factura_Cliente_Id.getText();

    if (id_cliente.equals("") || valorActualFactura.equals("0.0")) {
        JOptionPane.showMessageDialog(this,
                "Por favor indique el monto de la factura o ingrese los productos a ella");

    } else {/*from w  ww .  ja  v a  2 s.c om*/
        //System.err.println("Numero de filas" + TablaDeFacturaProducto.getRowCount());
        ArrayList<String> lineaCodigoProductos = new ArrayList<String>();
        ArrayList<String> lineaUnidadesProductos = new ArrayList<String>();
        ArrayList<String> lineaMontoProductos = new ArrayList<String>();
        double monto = 0d;
        try {
            double pago = Double.parseDouble(
                    (String) JOptionPane.showInputDialog("Ingrese por favor el monto pagado por el cliente"));
            while (pago < 0.0) {
                pago = Double.parseDouble((String) JOptionPane.showInputDialog(
                        "El pago debe ser positivo \nIngrese por favor el monto pagado por el cliente"));

            }

            double prestamo = Double.parseDouble(valorActualPrestamo.getText());
            double montoFactura = Double.parseDouble(valorActualFactura.getText());
            while (montoFactura - pago < 0.0) {
                pago = Double.parseDouble((String) JOptionPane.showInputDialog(
                        "El pago no debe ser superior al monto de la factura \nIngrese por favor el monto pagado por el cliente"));

            }
            if (prestamo - montoFactura <= 0.0) {
                int opcion = JOptionPane.showConfirmDialog(this,
                        "Con este prstamo el cliente excede su limite de prestamos. \n Desea continuar?",
                        "Mensaje del sistema", JOptionPane.YES_NO_OPTION);
                if (opcion != JOptionPane.YES_OPTION) {
                    return;
                }

            }

            for (int i = 0; i < TablaDeFacturaProducto.getRowCount(); i++) {
                /*
                 * Fila 0: ID producto
                 * Fila 4: Cantidad
                 */
                String ProductoId = String.valueOf(TablaDeFacturaProducto.getValueAt(i, 0));
                lineaCodigoProductos.add(ProductoId);

                int numeroUnidades = Integer.parseInt(String.valueOf(TablaDeFacturaProducto.getValueAt(i, 4)));

                String unidades = String.valueOf(numeroUnidades);
                lineaUnidadesProductos.add(unidades);

                double valorUnitario = Double
                        .parseDouble(String.valueOf(TablaDeFacturaProducto.getValueAt(i, 5)));
                double valorProductoTotal = numeroUnidades * valorUnitario;
                lineaMontoProductos.add(String.valueOf(valorProductoTotal));

                monto += valorProductoTotal;
            }

            if (TablaDeFacturaProducto.getRowCount() == 0) {
                monto = Double.parseDouble(valorActualFactura.getText());
            }

            String estado = "";
            if (monto == pago) {
                estado = "pagado";
            } else {
                estado = "fiado";
            }

            ControladorFactura controladorFactura = new ControladorFactura();
            //String[] selection = {"cliente_id", "fecha", "estado", "identificacionCliente"};
            Calendar calendario = Calendar.getInstance();
            String dia = Integer.toString(calendario.get(Calendar.DATE));
            String mes = Integer.toString(calendario.get(Calendar.MONTH)) + 1;
            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;
            String[] selection = { id_cliente, fecha, estado, String.valueOf(monto) };
            ArrayList<String[]> facturaActual = controladorFactura.insertFactura(selection);

            //Ingresar productos
            if (TablaDeFacturaProducto.getRowCount() > 0) {
                ControladorFactura_Productos controladorFactura_Productos = new ControladorFactura_Productos();
                for (int i = 0; i < lineaCodigoProductos.size(); i++) {
                    //        String [] selection = {"factura_id","producto_id","unidades","precio"};
                    String[] insertarLineaProducto = { facturaActual.get(0)[0], lineaCodigoProductos.get(i),
                            lineaUnidadesProductos.get(i), lineaMontoProductos.get(i) };
                    controladorFactura_Productos.insertFactura_Productos(insertarLineaProducto);
                }
            }
            //Ingresar flujo factura
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            // String [] selection = {"factura_id","tipo_flujo","fecha","identificacionCliente"};

            String value[] = { facturaActual.get(0)[0], "abono", fecha, String.valueOf(pago) };
            controladorFlujoFactura.insertFlujo_Factura(value);

            String value2[] = { facturaActual.get(0)[0], "deuda", fecha, String.valueOf(monto) };
            controladorFlujoFactura.insertFlujo_Factura(value2);

            botonEstablecerMontoFactura.setEnabled(false);
            botonAgregarProducto.setEnabled(false);
            botonGuardarFactura.setEnabled(false);
            jTextField_Factura_Cliente_Id.setText("");

            DefaultTableModel modeloTabla = (DefaultTableModel) TablaDeFacturaProducto.getModel();

            for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                modeloTabla.removeRow(i);
            }

            modeloTabla.setRowCount(0);
            TablaDeFacturaProducto.setModel(modeloTabla);

            Object opciones[] = { "Cerrar", "Imprimir", "Guardar en disco" };
            GenerarFactura generarFactura = new GenerarFactura();
            int opcion = JOptionPane.showOptionDialog(this,
                    "Se ha guardado la factura con xito\nQue desea hacer?", "Elija una opcin",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opciones, null);

            switch (opcion) {
            case 1:
                generarFactura.imprimirFactura(Integer.parseInt(facturaActual.get(0)[0]), this);
                break;
            case 2:
                PDDocument documento = generarFactura.crearFactura(Integer.parseInt(facturaActual.get(0)[0]),
                        this);
                JFileChooser fc = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivo PDF", "pdf", "text");
                fc.setFileFilter(filter);
                fc.showSaveDialog(this);
                if (fc.getSelectedFile() != null) {
                    File selectedFile = fc.getSelectedFile();
                    try {

                        documento.save(selectedFile + ".pdf");
                        JOptionPane.showMessageDialog(this, "El archivo ha sido guardado en disco");

                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this, "EL Archivo no se puede leer!");
                    }
                }
                break;

            default:
                break;
            }

            nombreClienteCrearFactura.setText("");
            IdentificacionClienteBuscarFactura.setText("");
            valorActualPrestamo.setText("");
            jTextField_Factura_Cliente_Id.setText("");
            jTextField_Factura_Producto_Nombre.setText("");
            jTextField_Factura_Producto_Descripcion.setText("");
            valorMontoFactura.setText("");
            valorActualFactura.setText("0.0");
            valorActualPrestamo.setText("0.0");
            botonGuardarFactura.setEnabled(false);
            botonEstablecerMontoFactura.setEnabled(false);
            botonAgregarProducto.setEnabled(false);
        } catch (Exception e) {
        }

    }

}

From source file:interfaces.InterfazPrincipal.java

private void TablaDeClientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaDeClientesMouseClicked
    // TODO add your handling code here:
    int fila = TablaDeClientes.getSelectedRow();
    int identificacion = (int) TablaDeClientes.getValueAt(fila, 0);

    final ControladorCliente controladorCliente = new ControladorCliente();
    ArrayList<Cliente> listaClientes = controladorCliente.obtenerClientes("", identificacion);
    final Cliente clienteActual = listaClientes.get(0);

    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Editar clientes");
    dialogoEditar.setSize(600, 310);//from w  ww  .j  av  a2s  . c  o m
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

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

    JLabel editarTextoPrincipalDialogo = new JLabel("Editar clientes");
    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);

    c.insets = new Insets(0, 5, 10, 0);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 40;
    JLabel editarNombreClienteDialogo = new JLabel("Nombre:");
    panelDialogo.add(editarNombreClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 15, 10, 15);
    final JTextField valorEditarNombreClienteDialogo = new JTextField();
    valorEditarNombreClienteDialogo.setText(clienteActual.getNombre());
    panelDialogo.add(valorEditarNombreClienteDialogo, c);

    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 40;
    c.insets = new Insets(0, 5, 10, 0);
    JLabel editarCelularClienteDialogo = new JLabel("Celular:");
    panelDialogo.add(editarCelularClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 15, 10, 15);

    final JTextField valorEditarCelularClienteDialogo = new JTextField();
    valorEditarCelularClienteDialogo.setText(clienteActual.getNumero_celular());
    panelDialogo.add(valorEditarCelularClienteDialogo, c);
    c.gridx = 2;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 40;
    c.insets = new Insets(0, 5, 10, 0);
    JLabel editarMontoClienteDialogo = new JLabel("Monto a prestar:");
    panelDialogo.add(editarMontoClienteDialogo, c);

    c.gridx = 3;
    c.gridy = 2;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 15, 10, 15);
    final JTextField valorEditarMontoClienteDialogo = new JTextField();
    valorEditarMontoClienteDialogo.setText(String.valueOf(clienteActual.getMonto_prestamo()));
    panelDialogo.add(valorEditarMontoClienteDialogo, c);

    c.gridx = 2;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 40;
    c.insets = new Insets(0, 15, 10, 0);
    JLabel editarTelefonoClienteDialogo = new JLabel("Telefono:");
    panelDialogo.add(editarTelefonoClienteDialogo, c);

    c.gridx = 3;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 100;
    c.insets = new Insets(0, 0, 10, 0);
    final JTextField valorEditarTelefonoClienteDialogo = new JTextField();
    valorEditarTelefonoClienteDialogo.setText(clienteActual.getNumero_telefono());
    panelDialogo.add(valorEditarTelefonoClienteDialogo, c);

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

    JLabel editarAddressClienteDialogo = new JLabel("Direccin:");
    panelDialogo.add(editarAddressClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 3;
    c.gridwidth = 3;
    c.ipadx = 400;
    c.insets = new Insets(0, 15, 10, 0);
    final JTextField valorEditarAddressClienteDialogo = new JTextField();
    valorEditarAddressClienteDialogo.setText(clienteActual.getDireccion());
    panelDialogo.add(valorEditarAddressClienteDialogo, c);

    c.gridx = 0;
    c.gridy = 4;
    c.gridwidth = 2;
    c.ipadx = 100;
    c.insets = new Insets(15, 40, 0, 0);
    JButton botonGuardarClienteDialogo = new JButton("Guardar");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 2;
    c.gridy = 4;
    c.gridwidth = 2;
    c.insets = new Insets(15, 40, 0, 0);
    c.ipadx = 100;

    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

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

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            try {
                clienteActual.setDireccion(valorEditarAddressClienteDialogo.getText());
                clienteActual.setMonto_prestamo(Double.parseDouble(valorEditarMontoClienteDialogo.getText()));
                clienteActual.setNombre(valorEditarNombreClienteDialogo.getText());
                clienteActual.setNumero_celular(valorEditarCelularClienteDialogo.getText());
                clienteActual.setNumero_telefono(valorEditarTelefonoClienteDialogo.getText());

                controladorCliente.editarCliente(clienteActual);
                JOptionPane.showMessageDialog(dialogoEditar, "Se ha editado el cliente xitosamente");
                dialogoEditar.dispose();

                //Refrescar busqueda actual
                String nombreCliente = nombreClienteBusqueda.getText();

                int identificacionClienteInt = 0;

                ControladorCliente controladorCliente = new ControladorCliente();

                ArrayList<Cliente> listaDeClientes = controladorCliente.obtenerClientes(nombreCliente,
                        identificacionClienteInt);

                //Agregar filas
                DefaultTableModel modelo = (DefaultTableModel) TablaDeClientes.getModel();

                for (int i = 0; i < modelo.getRowCount(); i++) {
                    modelo.removeRow(i);
                }
                modelo.setRowCount(0);
                for (int i = 0; i < listaDeClientes.size(); i++) {
                    Cliente cliente = listaDeClientes.get(i);
                    Object[] fila = new Object[4];
                    fila[0] = cliente.getCliente_id();
                    fila[1] = cliente.getNombre();
                    fila[2] = cliente.getMonto_prestamo();
                    //button.setText("<HTML>Click the <FONT color=\"#000099\"><U>link "+i+"</U></FONT>"+ " to go to the Java website.</HTML>");

                    fila[3] = "Editar";
                    modelo.addRow(fila);

                }

                TablaDeClientes.setModel(modelo);

            } catch (Exception event) {

                JOptionPane.showMessageDialog(dialogoEditar, "El valor del monto debe ser numrico");

            }

        }
    });

    dialogoEditar.setVisible(true);
    /*Action mostrarMensaje;
     mostrarMensaje = new AbstractAction() {
     @Override
     public void actionPerformed(ActionEvent e) {
     JTable table = (JTable) e.getSource();
     int modelRow = Integer.valueOf(e.getActionCommand());
     ((DefaultTableModel) table.getModel()).removeRow(modelRow);
     }
     };
     ButtonColumn buttonColumn = new ButtonColumn(TablaDeClientes, mostrarMensaje, 3);
     buttonColumn.setMnemonic(KeyEvent.VK_E);*/
}

From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_demand.java

private List<JComponent> getExtraOptions(final int row, final Object itemId) {
    List<JComponent> options = new LinkedList<JComponent>();
    final int numRows = model.getRowCount();
    final NetPlan netPlan = callback.getDesign();
    final List<Demand> tableVisibleDemands = getVisibleElementsInTable();

    JMenuItem offeredTrafficToAll = new JMenuItem("Set offered traffic to all");
    offeredTrafficToAll.addActionListener(new ActionListener() {
        @Override//from   w  ww  .  j a v  a 2s  .  c o m
        public void actionPerformed(ActionEvent e) {
            double h_d;

            while (true) {
                String str = JOptionPane.showInputDialog(null, "Offered traffic volume",
                        "Set traffic value to all demands in the table", JOptionPane.QUESTION_MESSAGE);
                if (str == null)
                    return;

                try {
                    h_d = Double.parseDouble(str);
                    if (h_d < 0)
                        throw new RuntimeException();

                    break;
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog("Please, introduce a non-negative number",
                            "Error setting offered traffic");
                }
            }

            NetPlan netPlan = callback.getDesign();

            try {
                for (Demand d : tableVisibleDemands)
                    d.setOfferedTraffic(h_d);
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(),
                        "Unable to set offered traffic to all demands in the table");
            }
        }
    });
    options.add(offeredTrafficToAll);

    JMenuItem scaleOfferedTrafficToAll = new JMenuItem("Scale offered traffic all demands in the table");
    scaleOfferedTrafficToAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            double scalingFactor;

            while (true) {
                String str = JOptionPane.showInputDialog(null,
                        "Scaling factor to multiply to all offered traffics", "Scale offered traffic",
                        JOptionPane.QUESTION_MESSAGE);
                if (str == null)
                    return;

                try {
                    scalingFactor = Double.parseDouble(str);
                    if (scalingFactor < 0)
                        throw new RuntimeException();

                    break;
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog("Please, introduce a non-negative number",
                            "Error setting offered traffic");
                }
            }

            try {
                for (Demand d : tableVisibleDemands)
                    d.setOfferedTraffic(d.getOfferedTraffic() * scalingFactor);
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to scale demand offered traffics");
            }
        }
    });
    options.add(scaleOfferedTrafficToAll);

    JMenuItem setServiceTypes = new JMenuItem(
            "Set traversed resource types (to one or all demands in the table)");
    setServiceTypes.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            NetPlan netPlan = callback.getDesign();
            try {
                Demand d = netPlan.getDemandFromId((Long) itemId);
                String[] headers = StringUtils.arrayOf("Order", "Type");
                Object[][] data = { null, null };
                DefaultTableModel model = new ClassAwareTableModelImpl(data, headers);
                AdvancedJTable table = new AdvancedJTable(model);
                JButton addRow = new JButton("Add new traversed resource type");
                addRow.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Object[] newRow = { table.getRowCount(), "" };
                        ((DefaultTableModel) table.getModel()).addRow(newRow);
                    }
                });
                JButton removeRow = new JButton("Remove selected");
                removeRow.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ((DefaultTableModel) table.getModel()).removeRow(table.getSelectedRow());
                        for (int t = 0; t < table.getRowCount(); t++)
                            table.getModel().setValueAt(t, t, 0);
                    }
                });
                JButton removeAllRows = new JButton("Remove all");
                removeAllRows.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        while (table.getRowCount() > 0)
                            ((DefaultTableModel) table.getModel()).removeRow(0);
                    }
                });
                List<String> oldTraversedResourceTypes = d.getServiceChainSequenceOfTraversedResourceTypes();
                Object[][] newData = new Object[oldTraversedResourceTypes.size()][headers.length];
                for (int i = 0; i < oldTraversedResourceTypes.size(); i++) {
                    newData[i][0] = i;
                    newData[i][1] = oldTraversedResourceTypes.get(i);
                }
                ((DefaultTableModel) table.getModel()).setDataVector(newData, headers);
                JPanel pane = new JPanel();
                JPanel pane2 = new JPanel();
                pane.setLayout(new BorderLayout());
                pane2.setLayout(new BorderLayout());
                pane.add(new JScrollPane(table), BorderLayout.CENTER);
                pane2.add(addRow, BorderLayout.WEST);
                pane2.add(removeRow, BorderLayout.EAST);
                pane2.add(removeAllRows, BorderLayout.SOUTH);
                pane.add(pane2, BorderLayout.SOUTH);
                final String[] optionsArray = new String[] { "Set to selected demand", "Set to all demands",
                        "Cancel" };
                int result = JOptionPane.showOptionDialog(null, pane, "Set traversed resource types",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, optionsArray,
                        optionsArray[0]);
                if ((result != 0) && (result != 1))
                    return;
                final boolean setToAllDemands = (result == 1);
                List<String> newTraversedResourcesTypes = new LinkedList<>();
                for (int j = 0; j < table.getRowCount(); j++) {
                    String travResourceType = table.getModel().getValueAt(j, 1).toString();
                    newTraversedResourcesTypes.add(travResourceType);
                }
                if (setToAllDemands) {
                    for (Demand dd : tableVisibleDemands)
                        if (!dd.getRoutes().isEmpty())
                            throw new Net2PlanException(
                                    "It is not possible to set the resource types traversed to demands with routes");
                    for (Demand dd : tableVisibleDemands)
                        dd.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes);
                } else {
                    if (!d.getRoutes().isEmpty())
                        throw new Net2PlanException(
                                "It is not possible to set the resource types traversed to demands with routes");
                    d.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes);
                }
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set traversed resource types");
            }
        }

    });
    options.add(setServiceTypes);

    if (itemId != null && netPlan.isMultilayer()) {
        final long demandId = (long) itemId;
        if (netPlan.getDemandFromId(demandId).isCoupled()) {
            JMenuItem decoupleDemandItem = new JMenuItem("Decouple demand");
            decoupleDemandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    netPlan.getDemandFromId(demandId).decouple();
                    model.setValueAt("", row, 3);
                    callback.getVisualizationState().resetPickedState();
                    callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                }
            });

            options.add(decoupleDemandItem);
        } else {
            JMenuItem createUpperLayerLinkFromDemandItem = new JMenuItem("Create upper layer link from demand");
            createUpperLayerLinkFromDemandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                    final JComboBox layerSelector = new WiderJComboBox();
                    for (long layerId : layerIds) {
                        if (layerId == netPlan.getNetworkLayerDefault().getId())
                            continue;

                        final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                        String layerLabel = "Layer " + layerId;
                        if (!layerName.isEmpty())
                            layerLabel += " (" + layerName + ")";

                        layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                    }

                    layerSelector.setSelectedIndex(0);

                    JPanel pane = new JPanel();
                    pane.add(new JLabel("Select layer: "));
                    pane.add(layerSelector);

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the upper layer to create the link",
                                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                    .getObject();
                            netPlan.getDemandFromId(demandId)
                                    .coupleToNewLinkCreated(netPlan.getNetworkLayerFromId(layerId));
                            callback.getVisualizationState()
                                    .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                            callback.updateVisualizationAfterChanges(
                                    Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error creating upper layer link from demand");
                        }
                    }
                }
            });

            options.add(createUpperLayerLinkFromDemandItem);

            JMenuItem coupleDemandToLink = new JMenuItem("Couple demand to upper layer link");
            coupleDemandToLink.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                    final JComboBox layerSelector = new WiderJComboBox();
                    final JComboBox linkSelector = new WiderJComboBox();
                    for (long layerId : layerIds) {
                        if (layerId == netPlan.getNetworkLayerDefault().getId())
                            continue;

                        final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                        String layerLabel = "Layer " + layerId;
                        if (!layerName.isEmpty())
                            layerLabel += " (" + layerName + ")";

                        layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                    }

                    layerSelector.addItemListener(new ItemListener() {
                        @Override
                        public void itemStateChanged(ItemEvent e) {
                            if (layerSelector.getSelectedIndex() >= 0) {
                                long selectedLayerId = (Long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                NetworkLayer selectedLayer = netPlan.getNetworkLayerFromId(selectedLayerId);

                                linkSelector.removeAllItems();
                                Collection<Link> links_thisLayer = netPlan.getLinks(selectedLayer);
                                for (Link link : links_thisLayer) {
                                    if (link.isCoupled())
                                        continue;

                                    String originNodeName = link.getOriginNode().getName();
                                    String destinationNodeName = link.getDestinationNode().getName();

                                    linkSelector.addItem(StringLabeller.unmodifiableOf(link.getId(),
                                            "e" + link.getIndex() + " [n" + link.getOriginNode().getIndex()
                                                    + " (" + originNodeName + ") -> n"
                                                    + link.getDestinationNode().getIndex() + " ("
                                                    + destinationNodeName + ")]"));
                                }
                            }

                            if (linkSelector.getItemCount() == 0) {
                                linkSelector.setEnabled(false);
                            } else {
                                linkSelector.setSelectedIndex(0);
                                linkSelector.setEnabled(true);
                            }
                        }
                    });

                    layerSelector.setSelectedIndex(-1);
                    layerSelector.setSelectedIndex(0);

                    JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]"));
                    pane.add(new JLabel("Select layer: "));
                    pane.add(layerSelector, "growx, wrap");
                    pane.add(new JLabel("Select link: "));
                    pane.add(linkSelector, "growx, wrap");

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the upper layer link", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                    .getObject();
                            long linkId;
                            try {
                                linkId = (long) ((StringLabeller) linkSelector.getSelectedItem()).getObject();
                            } catch (Throwable ex) {
                                throw new RuntimeException("No link was selected");
                            }

                            netPlan.getDemandFromId(demandId)
                                    .coupleToUpperLayerLink(netPlan.getLinkFromId(linkId));
                            callback.getVisualizationState().resetPickedState();
                            callback.updateVisualizationAfterChanges(
                                    Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error coupling upper layer link to demand");
                        }
                    }
                }
            });

            options.add(coupleDemandToLink);
        }

        if (numRows > 1) {
            JMenuItem decoupleAllDemandsItem = null;
            JMenuItem createUpperLayerLinksFromDemandsItem = null;

            final Set<Demand> coupledDemands = tableVisibleDemands.stream().filter(d -> d.isCoupled())
                    .collect(Collectors.toSet());
            if (!coupledDemands.isEmpty()) {
                decoupleAllDemandsItem = new JMenuItem("Decouple all demands");
                decoupleAllDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        for (Demand d : new LinkedHashSet<Demand>(coupledDemands))
                            d.decouple();
                        int numRows = model.getRowCount();
                        for (int i = 0; i < numRows; i++)
                            model.setValueAt("", i, 3);
                        callback.getVisualizationState().resetPickedState();
                        callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.DEMAND));
                        callback.getUndoRedoNavigationManager().addNetPlanChange();
                    }
                });
            }

            if (coupledDemands.size() < tableVisibleDemands.size()) {
                createUpperLayerLinksFromDemandsItem = new JMenuItem(
                        "Create upper layer links from uncoupled demands");
                createUpperLayerLinksFromDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                        final JComboBox layerSelector = new WiderJComboBox();
                        for (long layerId : layerIds) {
                            if (layerId == netPlan.getNetworkLayerDefault().getId())
                                continue;

                            final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                            String layerLabel = "Layer " + layerId;
                            if (!layerName.isEmpty())
                                layerLabel += " (" + layerName + ")";

                            layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                        }

                        layerSelector.setSelectedIndex(0);

                        JPanel pane = new JPanel();
                        pane.add(new JLabel("Select layer: "));
                        pane.add(layerSelector);

                        while (true) {
                            int result = JOptionPane.showConfirmDialog(null, pane,
                                    "Please select the upper layer to create links",
                                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                            if (result != JOptionPane.OK_OPTION)
                                return;

                            try {
                                long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                NetworkLayer layer = netPlan.getNetworkLayerFromId(layerId);
                                for (Demand demand : tableVisibleDemands)
                                    if (!demand.isCoupled())
                                        demand.coupleToNewLinkCreated(layer);

                                callback.getVisualizationState()
                                        .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                                callback.updateVisualizationAfterChanges(
                                        Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                                callback.getUndoRedoNavigationManager().addNetPlanChange();
                                break;
                            } catch (Throwable ex) {
                                ErrorHandling.showErrorDialog(ex.getMessage(),
                                        "Error creating upper layer links");
                            }
                        }
                    }
                });
            }

            if (!options.isEmpty()
                    && (decoupleAllDemandsItem != null || createUpperLayerLinksFromDemandsItem != null)) {
                options.add(new JPopupMenu.Separator());
                if (decoupleAllDemandsItem != null)
                    options.add(decoupleAllDemandsItem);
                if (createUpperLayerLinksFromDemandsItem != null)
                    options.add(createUpperLayerLinksFromDemandsItem);
            }

        }
    }

    return options;
}