Вы находитесь на странице: 1из 7

1

Formulario Personas

package Formulario;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import Prg.Conexion;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author wily
*/
public class frmProducto extends javax.swing.JDialog {
Conexion nCon; //Conexion de la base de datos
String sentencia, idma, fechaInsert;
Statement ejecutar;//variable para ejecucion de sentencias
DecimalFormat numeros = new DecimalFormat("##,###,###");
ResultSet resultado;//variable para almacenar resultado de consultas
SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
DefaultTableModel mitabla = new DefaultTableModel();
char operacion;

public frmProducto(java.awt.Frame parent, boolean modal) {


super(parent, modal);
initComponents();
this.setLocationRelativeTo(null);
this.setResizable(false);
try {
ejecutar = nCon.getConexion().createStatement();
} catch (SQLException ex) {
Logger.getLogger(frmPersonas.class.getName()).log(Level.SEVERE, null, ex);
}
CargarComboM();
mitabla.addColumn("Codigo");
mitabla.addColumn("NombreProducto");
mitabla.addColumn("Precio Costo");
mitabla.addColumn("Precio Venta");
mitabla.addColumn("Nombre Marca");
modoEdicion(false);
mostrarDatos();
}
Validacion de campo
private void txtPrecioVActionPerformed(java.awt.event.ActionEvent evt) {
try {
int c = Integer.parseInt(txtPrecioC.getText());
int v = Integer.parseInt(txtPrecioV.getText());
if (v > 0) {
} else {
txtPrecioV.setText(Integer.toString(v));
JOptionPane.showMessageDialog(this, "El Precio de Venta no puede ser menor que cero", "Dato
Incorrecto", JOptionPane.WARNING_MESSAGE);
}
if (v > c) {
} else {
txtPrecioV.setText(Integer.toString(v));
JOptionPane.showMessageDialog(this, "El Precio de Venta no puede ser menor que el precio de
costo", "Dato Incorrecto", JOptionPane.WARNING_MESSAGE);
txtPrecioV.grabFocus();
txtPrecioV.setText(null);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "El valor debe ser numerico", "Campo Numerico",
JOptionPane.ERROR_MESSAGE);
txtPrecioV.grabFocus();
txtPrecioV.setText(null);
}
}

Botones y cuadros de texto


private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {
accionModificar();
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
limpiarCuadros();
modoEdicion(false);
}
private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {
accionAgregar();
}
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {
accionGuardar();
}
private void cmbMarcaKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
traerMarcas();
}
}
private void tablaProductoMouseClicked(java.awt.event.MouseEvent evt) {
cargarCuadros();
}
private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
private void txtPrecioCActionPerformed(java.awt.event.ActionEvent evt) {
try {
int prac = Integer.parseInt(txtPrecioC.getText());
if (prac > 0) {
} else {
txtPrecioC.setText(Integer.toString(prac));
JOptionPane.showMessageDialog(this, "El Precio de Costo no puede ser menor que cero", "Dato
Incorrecto", JOptionPane.WARNING_MESSAGE);
txtPrecioC.grabFocus();
txtPrecioC.setText(null);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "El valor debe ser numerico", "Campo Numerico",
JOptionPane.ERROR_MESSAGE);
txtPrecioC.grabFocus();
txtPrecioC.setText(null);
}
}
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
accionEliminar();
}

Metodos
private void CargarComboM() {
sentencia = "SELECT * FROM marca_prod";
try {
resultado = ejecutar.executeQuery(sentencia);
while (resultado.next()) {
Object dato[] = new Object[1];
dato[0] = resultado.getObject(2).toString();
cmbMarca.addItem(dato[0]);
}
} catch (SQLException ex) {
Logger.getLogger(frmProducto.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void modoEdicion(boolean vL) {
txtNombre.setEnabled(vL);
txtIva.setEnabled(vL);
txtPrecioC.setEnabled(vL);
txtPrecioV.setEnabled(vL);
cmbMarca.setEnabled(vL);
tablaProducto.setEnabled(!vL);
btnAgregar.setEnabled(!vL);
btnGuardar.setEnabled(vL);
btnCancelar.setEnabled(vL);
btnModificar.setEnabled(!vL);
btnEliminar.setEnabled(!vL);
btnCerrar.setEnabled(!vL);
}
private void mostrarDatos() {
mitabla.setRowCount(0);
sentencia = "SELECT * FROM vistaProducto";
try {
resultado = ejecutar.executeQuery(sentencia);
while (resultado.next()) {
Object fila[] = new Object[8];
for (int x = 0; x < 8; x++) {
fila[x] = resultado.getObject(x + 1);
}
//asignar a tabla abstracta
mitabla.addRow(fila);
}
//asignar modelo a tabla(objeto)
tablaProducto.setModel(mitabla);
} catch (SQLException ex) {
Logger.getLogger(frmProducto.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void accionModificar() {


if(!txtNombre.getText().isEmpty()){
modoEdicion(true);
operacion = 'M';//indicamos la modificacion de registros
txtNombre.grabFocus();
}else{
JOptionPane.showMessageDialog(this,"Haga clic en el registro que desee modificar",
"Seleccione un Producto",JOptionPane.WARNING_MESSAGE);
}
}
private void limpiarCuadros() {
txtCodigo.setText(null);
txtNombre.setText(null);
txtPrecioC.setText(null);
txtPrecioV.setText(null);
txtIva.setText(null);
txtFecha.setText("");
cmbMarca.setSelectedIndex(-1);
}
private void accionAgregar() {
sentencia = "SELECT MAX(Id_Producto)FROM Producto";
try {
//ejecuta la consulta
resultado = ejecutar.executeQuery(sentencia);
//posicionamos al primer registro
resultado.next();
//obtenemos el valor entero del resultado
int xid = resultado.getInt(1);
//aumentar en 1
xid++;
//Asignar al cuadro codigo
txtCodigo.setText(Integer.toString(xid));
//Activar modo edicion (v)
modoEdicion(true);
//Enviar enfoque a nombre
txtNombre.grabFocus();
//Ingresar fecha por defecti
Date fecha = new Date();
txtFecha.setValue(fecha);
fechaInsert = formato.format(fecha);
operacion = 'A';//Indica que estamos agregando registro
} catch (SQLException ex) {
Logger.getLogger(frmProducto.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void accionGuardar() {
//Obtener valores de cuadros en variables
String v1 = txtCodigo.getText();
String v2 = txtNombre.getText();

String v3 = fechaInsert;
String v4 = txtPrecioC.getText();
String v5 = txtPrecioV.getText();
String v6 = txtIva.getText();
String v7 = idma;
//validar los datos
if(txtNombre.getText().isEmpty()){
JOptionPane.showMessageDialog(this,"No se puede dejar en blanco");
txtNombre.grabFocus();
}
else{
//sentencia de almacenamiento
if(operacion=='A'){
sentencia = "INSERT INTO Producto
VALUES('"+v1+"','"+v2+"','"+v3+"','"+v4+"','"+v5+"','"+v6+"','"+v7+"')";
}else{
sentencia = "UPDATE Producto SET
idmarca_prod='"+v2+"',nombre_prodo='"+v3+"',precio_costo='"+v4+"',precioventa='"+v5+"',porcentaje='
"+v6+"' WHERE cod_prod='"+v1+"'";
}
try {
ejecutar.executeUpdate(sentencia);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this,"Error al almacenar\n"+ex);
}
//limpiar cuadros y modo edicion a falso
limpiarCuadros();
modoEdicion(false);
mostrarDatos();
}
}
private void traerMarcas() {
String xmar = cmbMarca.getSelectedItem().toString();
sentencia = "SELECT * FROM marca_prod WHERE Descrip_marca ='" + xmar + "'";
try {
resultado = ejecutar.executeQuery(sentencia);
resultado.first();
idma = resultado.getObject(1).toString();
System.out.print(idma);
} catch (SQLException ex) {
Logger.getLogger(frmProducto.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void cargarCuadros() {
int fSel = tablaProducto.getSelectedRow();
//Obtener id de la fila seleccionada

String xid = tablaProducto.getValueAt(fSel,0).toString();


//Traemos los datos del funcionario desde la tabla
sentencia="SELECT * FROM Producto WHERE Id_Producto ='"+xid+"'";
try {
resultado= ejecutar.executeQuery(sentencia);
resultado.next();
//cargamos los valores en los cuadros de texto
txtCodigo.setText(resultado.getObject(1).toString());
txtNombre.setText(resultado.getObject(2).toString());
txtFecha.setText(resultado.getObject(3).toString());
txtPrecioC.setText(resultado.getObject(4).toString());
txtPrecioV.setText(resultado.getObject(5).toString());
txtIva.setText(resultado.getObject(6).toString());
idma = resultado.getObject(7).toString();
//PARA MARCAS
sentencia = "SELECT * FROM marca_prod WHERE idmarca_prod='"+idma+"'";
resultado = ejecutar.executeQuery(sentencia);
resultado.next();
cmbMarca.setSelectedItem(resultado.getObject(2));
} catch (SQLException ex) {
Logger.getLogger(frmProducto.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void accionEliminar() {
if(!txtNombre.getText().isEmpty()){
//obtenemos el id de la categoria
String xid = txtCodigo.getText();
sentencia = "DELETE FROM producto WHERE cod_prod ='"+xid+"'";
int resp = JOptionPane.showConfirmDialog(this,"Confirma la eliminacion?",
"Confirme",JOptionPane.YES_NO_OPTION);
if(resp==JOptionPane.YES_OPTION){
try {
ejecutar.executeUpdate(sentencia);
} catch (SQLException ex) {
Logger.getLogger(frmProducto.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
mostrarDatos();
limpiarCuadros();
}

Вам также может понравиться