JAVA Anotaciones de un sistema basico

22
public class Articulo extends javax.swing.JInternalFrame { ResultSet rs; ResultSet rsArti; char accion='z'; ConeccionBD bd = new ConeccionBD(); public Articulo() { initComponents(); setTitle("Formulario de Articulos"); ConeccionBD bd = new ConeccionBD(); cargacombo(); DefaultTableModel dm= new DefaultTableModel(){ public boolean isCellEditable(int row,int col){ return false; } }; dm.setDataVector( new Object[][]{}, new String[]{"Codigo","Nombre Articulo","Clasificacion"}); grdArticulo.setModel(dm); grdArticulo.getTableHeader().setReorderingAllowed(false); grdArticulo.getColumnModel().getColumn(0).setPreferredWidth(30); grdArticulo.getColumnModel().getColumn(1).setPreferredWidth(200); grdArticulo.getColumnModel().getColumn(1).setPreferredWidth(170); this.actualizarGrilla(); this.habilitar(false); } private void habilitar(boolean estado){ this.TxtNombre.setEditable(estado); this.cboClasificacion.setEnabled(estado); this.cmdNuevo.setEnabled(!estado); this.cmdModificar.setEnabled(!estado); this.cmdEliminar.setEnabled(!estado); this.cmdGuardar.setEnabled(false); this.cmdCancelar.setEnabled(estado); this.TxtCodigo.setText(""); this.TxtNombre.setText(""); if (this.accion=='M'||this.accion=='E'){ this.TxtCodigo.setEditable(true); this.TxtNombre.setEditable(!estado); this.TxtCodigo.requestFocus(); }else{ - 1 -

description

Ejemplo de un Sistema basico en JAVA con IDE NETBEANS. Con imagenes de los formularios. Tiene Insertar Registros ABM, Consultas y más

Transcript of JAVA Anotaciones de un sistema basico

Page 1: JAVA Anotaciones de un sistema basico

public class Articulo extends javax.swing.JInternalFrame { ResultSet rs; ResultSet rsArti; char accion='z'; ConeccionBD bd = new ConeccionBD();

public Articulo() { initComponents(); setTitle("Formulario de Articulos"); ConeccionBD bd = new ConeccionBD(); cargacombo(); DefaultTableModel dm= new DefaultTableModel(){ public boolean isCellEditable(int row,int col){ return false; } }; dm.setDataVector( new Object[][]{}, new String[]{"Codigo","Nombre Articulo","Clasificacion"}); grdArticulo.setModel(dm); grdArticulo.getTableHeader().setReorderingAllowed(false); grdArticulo.getColumnModel().getColumn(0).setPreferredWidth(30); grdArticulo.getColumnModel().getColumn(1).setPreferredWidth(200); grdArticulo.getColumnModel().getColumn(1).setPreferredWidth(170); this.actualizarGrilla(); this.habilitar(false); } private void habilitar(boolean estado){ this.TxtNombre.setEditable(estado); this.cboClasificacion.setEnabled(estado); this.cmdNuevo.setEnabled(!estado); this.cmdModificar.setEnabled(!estado); this.cmdEliminar.setEnabled(!estado); this.cmdGuardar.setEnabled(false); this.cmdCancelar.setEnabled(estado); this.TxtCodigo.setText(""); this.TxtNombre.setText("");

if (this.accion=='M'||this.accion=='E'){ this.TxtCodigo.setEditable(true); this.TxtNombre.setEditable(!estado); this.TxtCodigo.requestFocus(); }else{ this.TxtCodigo.setEditable(false); if(this.accion=='N'){ this.TxtNombre.requestFocus(); }else{ this.cmdNuevo.requestFocus(); } } }

- 1 -

Page 2: JAVA Anotaciones de un sistema basico

private void cargacombo(){ ConeccionBD bd = new ConeccionBD(); if(bd.estaConectado()){ try{boolean resultado = false; bd.cargarCombo("select * from clasificacion order by clasificacion",cboClasificacion); }catch(Exception ex){ JOptionPane.showMessageDialog(null, "Ocurrio Un error al actualizar la Base de Datos", "Articulo", JOptionPane.OK_OPTION+JOptionPane.ERROR_MESSAGE); } }else{ JOptionPane.showMessageDialog(null,"Se ha perdido la coneccion con la base de datos", "Error de coneccion",JOptionPane.OK_OPTION+JOptionPane.ERROR_MESSAGE); } } private void actualizarGrilla(){ ConeccionBD bd = new ConeccionBD(); ResultSet rsClasif; DefaultTableModel modelo=(DefaultTableModel)grdArticulo.getModel(); grdArticulo.selectAll(); int[]filas=grdArticulo.getSelectedRows(); for(int i=(filas.length-1 );i>=0;--i) modelo.removeRow(i); try{ String codigo,id_clasif,nombre,clasificacion; rs = (ResultSet) bd.dameLista("select * from articulo"); while(rs.next()){ codigo= rs.getString("codigo"); nombre= rs.getString("articulo"); id_clasif= rs.getString("id_clasificacion"); rsClasif = (ResultSet) bd.dameLista("select * from clasificacion where id_clasificacion = "+id_clasif); rsClasif.next(); clasificacion = rsClasif.getString("clasificacion"); modelo.addRow(new Object[]{codigo,nombre,clasificacion}); } }catch(Exception ex ){ JOptionPane.showMessageDialog(null,"Error al cargar datos","Error",JOptionPane.INFORMATION_MESSAGE); } } private void filtrarGrilla(){ DefaultTableModel modelo = (DefaultTableModel) grdArticulo.getModel(); TableRowSorter gridFiltrado = new TableRowSorter(modelo); gridFiltrado.setRowFilter(RowFilter.regexFilter(this.TxtCriterio.getText(), this.cboFiltron.getSelectedIndex())); grdArticulo.setRowSorter(gridFiltrado); }

private void habilitarGuardar(){ if ((this.TxtCodigo.getText().isEmpty()) || (this.TxtNombre.getText().isEmpty())) { this.cmdGuardar.setEnabled(false); }else{ this.cmdGuardar.setEnabled(true); }}

private void cmdSalirActionPerformed(java.awt.event.ActionEvent evt) { this.dispose();}

- 2 -

Page 3: JAVA Anotaciones de un sistema basico

MODIFICARprivate void cmdModificarActionPerformed(java.awt.event.ActionEvent evt) { this.accion='M';this.habilitar(true);}

ELIMINARprivate void cmdEliminarActionPerformed(java.awt.event.ActionEvent evt) { this.accion = 'E';this.habilitar(true);}

GUARDARprivate void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) { ConeccionBD bd = new ConeccionBD();String id_clasif = (((String[])this.cboClasificacion.getSelectedItem())[0]);try{boolean resultado = false; switch (accion){ case 'N': bd.insertarRegistro("articulo", this.TxtCodigo.getText()+ ",'"+this.TxtNombre.getText()+ "','"+id_clasif+ "',0,0"); break; case 'M': rs.first(); bd.actualizarRegistro("articulo", "articulo= '"+this.TxtNombre.getText()+ "', id_clasificacion= '"+id_clasif +"'", "codigo= "+this.TxtCodigo.getText()); break; } }catch(Exception ex){ JOptionPane.showMessageDialog(null,"Hubo un Error al Actualizar la Base de Datos","Articulo",JOptionPane.OK_OPTION+JOptionPane.ERROR_MESSAGE);}this.cmdCancelarActionPerformed(null);actualizarGrilla();}

NUEVOprivate void cmdNuevoActionPerformed(java.awt.event.ActionEvent evt) { ConeccionBD bd = new ConeccionBD();this.accion = 'N';this.habilitar(true);rs = (ResultSet) bd.dameLista("select max(codigo)from articulo");try{ rs.first(); this.TxtCodigo.setText(String.valueOf(rs.getInt(1)+1));}catch(Exception ex){}}

CANCELARprivate void cmdCancelarActionPerformed(java.awt.event.ActionEvent evt) { this.accion='Z';this.habilitar(false);}

- 3 -

Page 4: JAVA Anotaciones de un sistema basico

private void cboClasificacionFocusLost(java.awt.event.FocusEvent evt) { String codArt = (((String[])this.cboClasificacion.getSelectedItem())[0]);}

private void TxtCodigoFocusLost(java.awt.event.FocusEvent evt) { ConeccionBD bd = new ConeccionBD();if (!this.TxtCodigo.getText().isEmpty()){ rs = (ResultSet) bd.dameLista("select * from articulo where codigo= "+this.TxtCodigo.getText()); try{ rs.first(); if (rs.first()){ this.TxtNombre.setText(rs.getString("articulo")); Object cboValores; for (int i = 0; i<=this.cboClasificacion.getItemCount();i++){ cboValores = this.cboClasificacion.getItemAt(i); if ((((String[])cboValores)[0]).equals(rs.getString("id_clasificacion"))){ this.cboClasificacion.setSelectedIndex(i); break; } } this.cboClasificacionFocusLost(null); this.TxtCodigo.setEditable(false); if (this.accion=='E'){ boolean borrado=false; JOptionPane optionPane = new JOptionPane(); Object[] opc= {"SI","NO"}; int resp = optionPane.showOptionDialog(this, "Desea Eliminar el registro?", "ELIMINAR", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opc, opc[0]); if (resp==JOptionPane.YES_OPTION){ borrado=bd.borrarRegistroSinPreguntar("articulo", "codigo ="+this.TxtCodigo.getText()); } if (!borrado){ JOptionPane.showMessageDialog(null, "El registro no se ha eliminado", "Operacion Cancelada", JOptionPane.INFORMATION_MESSAGE); }else{ JOptionPane.showMessageDialog(null, "Registro eliminado", "ELIMINAR", JOptionPane.INFORMATION_MESSAGE); } this.cmdCancelarActionPerformed(null); this.actualizarGrilla(); }else{ this.cboClasificacion.setEnabled(true); this.TxtNombre.setEditable(true); this.TxtNombre.requestFocus(); } }else{ if (this.accion!='N'){ JOptionPane.showMessageDialog(null, "No existe el articulo", "Articulo", JOptionPane.OK_OPTION+JOptionPane.INFORMATION_MESSAGE); this.cmdCancelarActionPerformed(null); } } }catch(Exception ex){ JOptionPane.showMessageDialog(null, "Error al recuperar datos", "Articulo", JOptionPane.OK_OPTION); } }}

private void TxtCriterioKeyReleased(java.awt.event.KeyEvent evt) { this.filtrarGrilla();}

- 4 -

Page 5: JAVA Anotaciones de un sistema basico

public class InfVentas extends javax.swing.JInternalFrame { char opc = 'Z'; String variable; boolean bisiestor, valida;

public InfVentas() { initComponents(); ConeccionBD bd = new ConeccionBD(); bd.cargarCombo("select * from clientes order by id_cliente",cboCliente); bd.cargarCombo("select * from Articulo order by codigo",cboArticulo); }private void cmdVistaActionPerformed(java.awt.event.ActionEvent evt) { String consulta;consulta = "SELECT venta_cab.`nro_factura` AS Factura,"+ "venta_cab.`fecha` AS Fecha,"+ "clientes.`cliente` AS Cliente,"+ "venta_det.`id_articulo` AS Cod_Articulo,"+ "articulo.`articulo` AS Articulo,"+ "venta_det.`cantidad` AS Cantidad,"+ "venta_det.`precio` AS Precio,"+ "venta_det.`subtotal` AS Subtotal,"+ "venta_cab.`total` AS Total FROM"+ "`venta_cab` venta_cab INNER JOIN `venta_det` venta_det ON venta_cab.`nro_factura` = venta_det.`nro_factura`"+ "INNER JOIN `clientes` clientes ON venta_cab.`id_cliente` = clientes.`id_cliente`"+ "INNER JOIN `articulo` articulo ON venta_det.`id_articulo` = articulo.`codigo`";Integer numOpc = this.Opciones.getSelectedIndex();switch (numOpc){case 0:

- 5 -

Page 6: JAVA Anotaciones de un sistema basico

opc = 'F'; break;case 1: opc = 'C'; break;case 2: opc = 'A'; break;case 3: opc = 'T'; break;case 4: opc = 'M'; break;} switch (opc){case 'F': if (txtFecIni.getText().isEmpty()){ txtFecIni.setText(txtFecFin.getText()); } if (txtFecFin.getText().isEmpty()){ txtFecFin.setText(txtFecIni.getText()); } String FechaIni = txtFecIni.getText(); cambiarFecha(FechaIni); FechaIni = variable; String FechaFin = txtFecFin.getText(); cambiarFecha(FechaFin); FechaFin = variable; consulta = "SELECT venta_cab.`nro_factura` AS Factura,"+ "venta_cab.`fecha` AS Fecha,"+ "clientes.`cliente` AS Cliente,"+ "venta_det.`id_articulo` AS Cod_Articulo,"+ "articulo.`articulo` AS Articulo,"+ "venta_det.`cantidad` AS Cantidad,"+ "venta_det.`precio` AS Precio,"+ "venta_det.`subtotal` AS Subtotal,"+ "venta_cab.`total` AS Total FROM"+ "`venta_cab` venta_cab INNER JOIN `venta_det` venta_det ON venta_cab.`nro_factura` = venta_det.`nro_factura`"+ "INNER JOIN `clientes` clientes ON venta_cab.`id_cliente` = clientes.`id_cliente`"+ "INNER JOIN `articulo` articulo ON venta_det.`id_articulo` = articulo.`codigo`"+ "WHERE fecha BETWEEN '"+FechaIni+"' and '"+FechaFin+"' ORDER BY venta_cab.nro_factura" ; break;case 'C': String clientebusca = (((String[])this.cboCliente.getSelectedItem())[1]); consulta = "SELECT venta_cab.`nro_factura` AS Factura,"+ "venta_cab.`fecha` AS Fecha,"+ "clientes.`cliente` AS Cliente,"+ "venta_det.`id_articulo` AS Cod_Articulo,"+ "articulo.`articulo` AS Articulo,"+ "venta_det.`cantidad` AS Cantidad,"+ "venta_det.`precio` AS Precio,"+ "venta_det.`subtotal` AS Subtotal,"+ "venta_cab.`total` AS Total FROM"+ "`venta_cab` venta_cab INNER JOIN `venta_det` venta_det ON venta_cab.`nro_factura` = venta_det.`nro_factura`"+ "INNER JOIN `clientes` clientes ON venta_cab.`id_cliente` = clientes.`id_cliente`"+ "INNER JOIN `articulo` articulo ON venta_det.`id_articulo` = articulo.`codigo`"+ "WHERE cliente LIKE '%"+clientebusca+"%' ORDER BY venta_cab.nro_factura" ;break;case 'A': if (!this.txtCodArticulo.getText().isEmpty()){ String codarticulobusca = String.valueOf(this.txtCodArticulo.getText()); consulta = "SELECT venta_cab.`nro_factura` AS Factura,"+ "venta_cab.`fecha` AS Fecha,"+ "clientes.`cliente` AS Cliente,"+ "venta_det.`id_articulo` AS Cod_Articulo,"+

- 6 -

Page 7: JAVA Anotaciones de un sistema basico

"articulo.`articulo` AS Articulo,"+ "venta_det.`cantidad` AS Cantidad,"+ "venta_det.`precio` AS Precio,"+ "venta_det.`subtotal` AS Subtotal,"+ "venta_cab.`total` AS Total FROM"+ "`venta_cab` venta_cab INNER JOIN `venta_det` venta_det ON venta_cab.`nro_factura` = venta_det.`nro_factura`"+ "INNER JOIN `clientes` clientes ON venta_cab.`id_cliente` = clientes.`id_cliente`"+ "INNER JOIN `articulo` articulo ON venta_det.`id_articulo` = articulo.`codigo`"+ "WHERE id_articulo = '"+codarticulobusca+"' ORDER BY venta_cab.nro_factura" ; }else{ String articulobusca = (((String[])this.cboArticulo.getSelectedItem())[1]); consulta = "SELECT venta_cab.`nro_factura` AS Factura,"+ "venta_cab.`fecha` AS Fecha,"+ "clientes.`cliente` AS Cliente,"+ "venta_det.`id_articulo` AS Cod_Articulo,"+ "articulo.`articulo` AS Articulo,"+ "venta_det.`cantidad` AS Cantidad,"+ "venta_det.`precio` AS Precio,"+ "venta_det.`subtotal` AS Subtotal,"+ "venta_cab.`total` AS Total FROM"+ "`venta_cab` venta_cab INNER JOIN `venta_det` venta_det ON venta_cab.`nro_factura` = venta_det.`nro_factura`"+ "INNER JOIN `clientes` clientes ON venta_cab.`id_cliente` = clientes.`id_cliente`"+ "INNER JOIN `articulo` articulo ON venta_det.`id_articulo` = articulo.`codigo`"+ "WHERE articulo = '"+articulobusca+"' ORDER BY venta_cab.nro_factura" ; }break;case 'T': if (!this.txtFactura.getText().isEmpty()){ Integer facturabusca = Integer.valueOf(this.txtFactura.getText()); consulta = "SELECT venta_cab.`nro_factura` AS Factura,"+ "venta_cab.`fecha` AS Fecha,"+ "clientes.`cliente` AS Cliente,"+ "venta_det.`id_articulo` AS Cod_Articulo,"+ "articulo.`articulo` AS Articulo,"+ "venta_det.`cantidad` AS Cantidad,"+ "venta_det.`precio` AS Precio,"+ "venta_det.`subtotal` AS Subtotal,"+ "venta_cab.`total` AS Total FROM"+ "`venta_cab` venta_cab INNER JOIN `venta_det` venta_det ON venta_cab.`nro_factura` = venta_det.`nro_factura`"+ "INNER JOIN `clientes` clientes ON venta_cab.`id_cliente` = clientes.`id_cliente`"+ "INNER JOIN `articulo` articulo ON venta_det.`id_articulo` = articulo.`codigo`"+ "WHERE venta_cab.`nro_factura` ="+facturabusca+" ORDER BY venta_cab.nro_factura" ; }else{ }break;case 'M': String Fecha = txtFecha.getText(); if (txtFecha.getText().isEmpty()){ java.util.Date fechas = new Date(); Fecha = String.valueOf(fechas.getDate() + "-" + String.valueOf(fechas.getMonth() + 1) + "-" + String.valueOf(fechas.getYear() + 1900)); } cambiarFecha(Fecha);

Fecha = variable; consulta = "SELECT venta_cab.`nro_factura` AS Factura,"+ "venta_cab.`fecha` AS Fecha,"+ "clientes.`cliente` AS Cliente,"+ "venta_det.`id_articulo` AS Cod_Articulo,"+ "articulo.`articulo` AS Articulo,"+ "venta_det.`cantidad` AS Cantidad,"+ "venta_det.`precio` AS Precio,"+ "venta_det.`subtotal` AS Subtotal,"+ "venta_cab.`total` AS Total FROM"+ "`venta_cab` venta_cab INNER JOIN `venta_det` venta_det ON venta_cab.`nro_factura` = venta_det.`nro_factura`"+ "INNER JOIN `clientes` clientes ON venta_cab.`id_cliente` = clientes.`id_cliente`"+ "INNER JOIN `articulo` articulo ON venta_det.`id_articulo` = articulo.`codigo`"+

- 7 -

Page 8: JAVA Anotaciones de un sistema basico

"WHERE fecha BETWEEN '"+Fecha+"' and '"+Fecha+"' ORDER BY venta_cab.nro_factura" ;break;}

Listado lista = new Listado(); try { lista.mostrar("C:\\Julio_Project\\Informes\\Inf_Ventas.jasper",consulta); } catch (Exception e) { JOptionPane.showMessageDialog(null, "NO se encontro Archivo .jasper", "ERROR", JOptionPane.OK_OPTION); } }

private void cambiarFecha(String variable2){ String Anho, Mes, Dia; Anho = variable2.substring(6); Dia = variable2.substring(0, 2); Mes = variable2.substring(3, 5); Integer numMes = Integer.valueOf(Mes);

if (numMes<10){ Mes = "0"+String.valueOf(numMes); }else{ Mes = String.valueOf(numMes); }

Integer numDia = Integer.valueOf(Dia); if (numDia<10){ Dia = "0"+String.valueOf(numDia); }else{ Dia = String.valueOf(numDia); } variable2 = (Anho+"-"+Mes+"-"+Dia); variable = variable2; return; }

private void cmdSalirActionPerformed(java.awt.event.ActionEvent evt) { this.dispose();}

private void cboArticuloItemStateChanged(java.awt.event.ItemEvent evt) { this.txtCodArticulo.setText("");}

private void PanelClienteFocusGained(java.awt.event.FocusEvent evt) { opc = 'C';}

private void txtFecIniFocusLost(java.awt.event.FocusEvent evt) { valida = true; String FechaIni = txtFecIni.getText(); validarFecha(FechaIni); if (valida==false){ JOptionPane.showMessageDialog(null, "Fecha Invalida", "ERROR", JOptionPane.OK_OPTION); }}

- 8 -

Page 9: JAVA Anotaciones de un sistema basico

private void validarFecha(String variable3){

Integer año, mes, dia;año = Integer.valueOf(variable3.substring(6));dia = Integer.valueOf(variable3.substring(0, 2));mes = Integer.valueOf(variable3.substring(4, 5));

//JOptionPane.showMessageDialog(null, "Fecha= "+ dia + "-"+ mes + "-"+año, "ERROR", JOptionPane.OK_OPTION);

if (dia<0 || dia>31 || mes<0 || mes >12){valida=false;return;}else{ if ((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30){ valida=false; return; }else{ bisiesto(año); if (mes==2 && dia>28 && bisiestor){ valida=false; return; }else{ valida=true; return; } }}

}private void bisiesto(Integer año){

if (año%4!=0)bisiestor=false;elseif (año%400==0)bisiestor=true;elseif (año%100==0)bisiestor=false;elsebisiestor=true;return;}

- 9 -

Page 10: JAVA Anotaciones de un sistema basico

class DecimalRenderer extends DefaultTableCellRenderer{ DecimalFormat formatter; DecimalRenderer(String pattern){ this(new DecimalFormat(pattern)); } DecimalRenderer(DecimalFormat formatter){ this.formatter = formatter; setHorizontalAlignment (JLabel.RIGHT); } }

public class Ventas extends javax.swing.JInternalFrame { ConeccionBD bd = new ConeccionBD(); ResultSet rsCab; ResultSet rsDet; ResultSet rsCliente; ResultSet rsArticulo; /** Creates new form Ventas */ public Ventas() { initComponents(); setTitle("Formulario de Ventas - Articulos"); if (!bd.estaConectado()) { JOptionPane.showMessageDialog(null, "Error en la coneccion", "Base de Datos - ERROR!!!", JOptionPane.ERROR_MESSAGE); }else{ this.cboCliente.removeAllItems(); bd.cargarCombo("select * from clientes order by cliente", cboCliente); this.cboArticulo.removeAllItems(); bd.cargarCombo("select * from articulo", cboArticulo); } DefaultTableModel modelo = new DefaultTableModel(){ @Override public boolean isCellEditable (int row, int col){ return false; } }; this.habilitar(false);

- 10 -

Page 11: JAVA Anotaciones de un sistema basico

modelo.setDataVector( new Object [][]{}, new String[]{"Codigo","Cant.","Articulo","Precio","Subtotal"}); this.gridDetalle.setModel(modelo); this.gridDetalle.getTableHeader().setReorderingAllowed(false); this.gridDetalle.getColumnModel().getColumn(0).setPreferredWidth(80); this.gridDetalle.getColumnModel().getColumn(1).setPreferredWidth(60); this.gridDetalle.getColumnModel().getColumn(2).setPreferredWidth(300); this.gridDetalle.getColumnModel().getColumn(3).setPreferredWidth(80); this.gridDetalle.getColumnModel().getColumn(4).setPreferredWidth(90); this.gridDetalle.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); final DecimalFormat formatter = new DecimalFormat("###,##0,00"); this.gridDetalle.getColumn("Cant.").setCellRenderer(new DecimalRenderer (formatter)); this.gridDetalle.getColumn("Precio").setCellRenderer(new DecimalRenderer (formatter)); this.gridDetalle.getColumn("Subtotal").setCellRenderer(new DecimalRenderer (formatter)); }private void establecerFecha(){ Calendar calendario = Calendar.getInstance(); String anho = String.valueOf(calendario.get(Calendar.YEAR)); String mes; int numMes = Integer.valueOf(calendario.get(Calendar.MONTH)+1); if (numMes<10){ mes = "0"+String.valueOf(numMes); }else{ mes = String.valueOf(numMes); } String dia; int numDia = Integer.valueOf(calendario.get(Calendar.DAY_OF_MONTH)); if (numDia<10){ dia = "0"+String.valueOf(numDia); }else{ dia = String.valueOf(numDia); } this.txtFecha.setText(anho+"-"+mes+"-"+dia); } private void habilitar(boolean estado){ this.txtFactura.setEditable(false); this.txtCantidad.setEditable(estado); this.cboArticulo.setEnabled(estado); this.cboCliente.setEnabled(estado); this.cmdAnular.setEnabled(!estado); bd.cargarCombo("select * from articulo", cboArticulo); } private void limpiar(){ this.txtCantidad.setText(""); this.txtDireccion.setText(""); this.txtFactura.setText(""); this.txtPrecio.setText(""); this.txtRuc.setText(""); this.txtTotal.setText("0"); } private void vaciarGrilla(){ DefaultTableModel modelo = (DefaultTableModel) this.gridDetalle.getModel(); this.gridDetalle.selectAll(); int[] cant_filas = this.gridDetalle.getSelectedRows(); for (int i=(cant_filas.length - 1); i>=0;i--){ modelo.removeRow(cant_filas[i]); } } private void controlError (String msj) { JOptionPane.showMessageDialog(null, "Error al intentar acceder a la Base de Datos\n"+msj, "ERROR DE CONECTIVIDAD", JOptionPane.ERROR_MESSAGE); this.cmdCancelarActionPerformed(null); }

- 11 -

Page 12: JAVA Anotaciones de un sistema basico

private void cboClienteFocusLost(java.awt.event.FocusEvent evt) { String codclie = (((String[])this.cboCliente.getSelectedItem())[0]);rsCliente = bd.dameLista("select direccion, ruc from clientes where id_cliente= "+codclie); try{ rsCliente.first(); this.txtDireccion.setText(rsCliente.getString("direccion")); this.txtRuc.setText(rsCliente.getString("ruc")); rsCliente.close(); }catch (Exception ex) { this.controlError(ex.toString()); }}

private void txtCantidadKeyReleased(java.awt.event.KeyEvent evt) { if (this.txtCantidad.getText().isEmpty() || this.txtPrecio.getText().isEmpty()){ this.cmdAgregar.setEnabled(false);}else{ this.cmdAgregar.setEnabled(true);}}

private void gridDetalleFocusGained(java.awt.event.FocusEvent evt) { // si la cantidad de registros del grid es mayot a 0, habilita el boton quitarif (this.gridDetalle.getRowCount() > 0){ this.cmdQuitar.setEnabled(true);}}

- 12 -

Page 13: JAVA Anotaciones de un sistema basico

AGREGARprivate void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) { ResultSet rsStock;if (this.txtCantidad.getText().isEmpty()){ JOptionPane.showMessageDialog(null, "Vuelva a introducir la cantidad", "Ventas", JOptionPane.INFORMATION_MESSAGE); this.txtCantidad.requestFocus();}else{ boolean yaexiste= false, sobrepasa= false; DefaultTableModel modelo = (DefaultTableModel) this.gridDetalle.getModel(); int cant = Integer.parseInt(this.txtCantidad.getText()); int precio = Integer.parseInt(this.txtPrecio.getText()); int subtotal = cant * precio; String cod_art = (((String [])this.cboArticulo.getSelectedItem())[0]); String nom_art = (((String [])this.cboArticulo.getSelectedItem())[1]); rsStock = bd.dameLista("select cantidad from articulo where codigo= "+cod_art); try{ rsStock.first(); if (cant>rsStock.getInt("cantidad")){ sobrepasa = true; } }catch (SQLException ex){ this.controlError(ex.toString()); } Integer cant_grilla, sub_grilla; String cod_grilla; Integer cant_registros = this.gridDetalle.getRowCount(); if (cant_registros > 0 && !sobrepasa){ for (int i=0; i< cant_registros; i++){ cod_grilla = (String) gridDetalle.getValueAt(i, 0); if (cod_grilla.equalsIgnoreCase(cod_art)){ cant_grilla = (Integer) this.gridDetalle.getValueAt(i, 1); sub_grilla = (Integer) this.gridDetalle.getValueAt(i, 4); int nuevaCant = (cant + cant_grilla); try{ if (nuevaCant <= rsStock.getInt("cantidad")) { int nuevoSub = subtotal + sub_grilla; this.gridDetalle.setValueAt((Object)nuevaCant, i, 1); this.gridDetalle.setValueAt((Object)nuevoSub, i, 4); }else{ sobrepasa = true; } }catch (SQLException ex) { this.controlError(ex.toString()); } yaexiste = true; } } } if (sobrepasa){ try{ JOptionPane.showMessageDialog(null, "Ha sobrepasado la cantidad existente en Stock: " + rsStock.getString("cantidad"), "Ventas", JOptionPane.INFORMATION_MESSAGE); }catch (SQLException ex) { this.controlError(ex.toString()); } }else{ if (!yaexiste){ modelo.addRow(new Object[]{cod_art, cant, nom_art, precio, subtotal}); this.cmdGuardar.setEnabled(true); } int v_total = Integer.parseInt(this.txtTotal.getText()) + subtotal; this.txtTotal.setText(String.valueOf(v_total)); } this.txtCantidad.setText(""); this.cmdAgregar.setEnabled(false); this.cboArticulo.requestFocus(); }}

- 13 -

Page 14: JAVA Anotaciones de un sistema basico

QUITARprivate void cmdQuitarActionPerformed(java.awt.event.ActionEvent evt) { int [] filaSeleccionada = this.gridDetalle.getSelectedRows();DefaultTableModel modelo = (DefaultTableModel) this.gridDetalle.getModel();if (filaSeleccionada.length >0){ for (int i = (filaSeleccionada.length - 1); i >=0; i--){ modelo.removeRow(filaSeleccionada[i]); } if (this.gridDetalle.getRowCount() < 1){ this.txtTotal.setText("0"); this.cmdGuardar.setEnabled(false); }else{ int subtotal = 0; int filas = this.gridDetalle.getRowCount(); for(int i = 0; i<filas; i++){ int sub_grilla = (Integer) this.gridDetalle.getValueAt(i, 4); subtotal = subtotal + sub_grilla; } this.txtTotal.setText(String.valueOf(subtotal)); } this.cboArticulo.requestFocus(); this.cmdQuitar.setEnabled(false);}else{ JOptionPane.showMessageDialog(null, "Para QUITAR un Articulo debe seleccionarlo primero", "QUITAR ARTICULO",JOptionPane.INFORMATION_MESSAGE); }}

private void txtFacturaFocusLost(java.awt.event.FocusEvent evt) { if (!this.txtFactura.getText().isEmpty()){ rsCab = bd.dameLista("select * from venta_cab where anulado = 0 and nro_factura= "+this.txtFactura.getText()); try{ if (rsCab.first()){ this.txtFecha.setText(rsCab.getString("fecha")); Object cboValores; for (int i = 0; i<=this.cboCliente.getItemCount();i++){ cboValores = this.cboCliente.getItemAt(i); if ((((String[])cboValores)[0]).equals(rsCab.getString("id_cliente"))){ this.cboCliente.setSelectedIndex(i); break; } } this.cboClienteFocusLost(null); rsDet = bd.dameLista("select * from venta_det where nro_factura= "+ this.txtFactura.getText()); DefaultTableModel modelo = (DefaultTableModel) this.gridDetalle.getModel(); int total=0; while (rsDet.next()){ rsArticulo = bd.dameLista("select articulo from articulo where codigo= "+ rsDet.getString("id_articulo")); rsArticulo.first(); String nom_art = rsArticulo.getString("articulo"); String id_art = rsDet.getString("id_articulo"); String cant = rsDet.getString("cantidad"); String precio = rsDet.getString("precio"); String subtotal = rsDet.getString("subtotal"); total = total + rsDet.getInt("subtotal"); modelo.addRow(new Object[]{id_art,cant,nom_art,precio,subtotal}); } this.txtTotal.setText(String.valueOf(total)); Object[] opciones={"Si","No"}; int resp= JOptionPane.showOptionDialog(null, "Esta seguro de ANULAR la factura? ", "Ventas", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opciones, opciones[0]); if(resp==JOptionPane.YES_OPTION){ rsDet.beforeFirst(); while (rsDet.next()){ bd.actualizarRegistro("articulo", "cantidad= cantidad + "+ rsDet.getString("cantidad"), "codigo= "+ rsDet.getString("id_articulo")); }

- 14 -

Page 15: JAVA Anotaciones de un sistema basico

} }else{ JOptionPane.showMessageDialog(null, "No se encuentra la Factura digitada o ya está anulada", "Ventas",JOptionPane.INFORMATION_MESSAGE); } }catch (Exception e){ this.controlError(e.toString()); }}this.establecerFecha();this.cmdCancelarActionPerformed(null);this.limpiar();}

private void cmdCancelarActionPerformed(java.awt.event.ActionEvent evt) { this.limpiar();this.habilitar(false);this.vaciarGrilla();this.cmdNuevo.requestFocus();}

private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) { boolean huboError = false;String cod_cliente = (((String []) this.cboCliente.getSelectedItem())[0]);String factura = this.txtFactura.getText();String fecha = this.txtFecha.getText();String total = this.txtTotal.getText();if (bd.insertarRegistro("venta_cab",factura+","+cod_cliente+",'"+fecha+"',"+total+",0")){ try{ int filas = this.gridDetalle.getRowCount(); String id_art, cant, precio, subtotal; for (int i=0;i<filas;i++){ id_art = this.gridDetalle.getValueAt(i, 0).toString(); cant = this.gridDetalle.getValueAt(i, 1).toString(); precio = this.gridDetalle.getValueAt(i, 3).toString(); subtotal = this.gridDetalle.getValueAt(i, 4).toString(); bd.insertarRegistro("venta_det", factura+","+id_art+","+cant+","+precio+","+subtotal); } }catch(Exception e){ huboError = true; this.controlError(e.toString()); }}else{ huboError = true;}if (huboError) { bd.borrarRegistroSinPreguntar("venta_cab", "nro_factura= "+factura); bd.borrarRegistroSinPreguntar("venta_det", "nro_factura= "+factura); JOptionPane.showMessageDialog(null, "Error al cargar Factura","ERROR", JOptionPane.ERROR_MESSAGE);}else{ try{ int filas = this.gridDetalle.getRowCount(); String id_art, cant; for (int i=0; i<filas;i++){ id_art = this.gridDetalle.getValueAt(i, 0).toString(); cant = this.gridDetalle.getValueAt(i, 1).toString(); bd.actualizarRegistro("articulo","cantidad= cantidad + "+cant,"codigo= "+id_art); } JOptionPane.showMessageDialog(null, "Factura registrada con Éxito!!!","Ventas", JOptionPane.INFORMATION_MESSAGE); }catch (Exception e){ bd.borrarRegistroSinPreguntar("venta_cab", "nro_factura= "+factura); bd.borrarRegistroSinPreguntar("venta_det", "nro_factura= "+factura); JOptionPane.showMessageDialog(null, "Error al actualizar","ERROR!", JOptionPane.ERROR_MESSAGE); }

- 15 -

Page 16: JAVA Anotaciones de un sistema basico

this.cmdCancelarActionPerformed(null);}}

private void cmdAnularActionPerformed(java.awt.event.ActionEvent evt) { this.txtFactura.setEditable(true);this.txtFactura.requestFocus();}

private void cmdNuevoActionPerformed(java.awt.event.ActionEvent evt) { this.habilitar(true);this.cboCliente.requestFocus();rsCab=bd.dameLista("select max(nro_factura) from venta_cab"); try{ rsCab.first(); this.txtFactura.setText(String.valueOf(rsCab.getInt(1)+1)); }catch (Exception ex) { this.controlError(ex.toString()); }}

private void cmdSalirActionPerformed(java.awt.event.ActionEvent evt) { this.dispose();} private void txtPrecioKeyReleased(java.awt.event.KeyEvent evt) { if (this.txtCantidad.getText().isEmpty() || this.txtPrecio.getText().isEmpty()){ this.cmdAgregar.setEnabled(false);}else{ this.cmdAgregar.setEnabled(true);}} private void cboArticuloItemStateChanged(java.awt.event.ItemEvent evt) {

cmdPrecioActionPerformed(null);

}

private void cmdPrecioActionPerformed(java.awt.event.ActionEvent evt) { ResultSet rs; String cod_art = (((String [])this.cboArticulo.getSelectedItem())[0]); //String nom_art = (((String [])this.cboArticulo.getSelectedItem())[1]); rs = bd.dameLista("select * from articulo where codigo = '" + cod_art + "'"); try { rs.first(); String resultadoart = rs.getString("precio"); this.txtPrecio.setText((resultadoart)); } catch (SQLException ex) { }}

- 16 -