You are on page 1of 125

Departamento de Ciencias de la Computación

Programación II

Proyecto:
Proyecto de fin de semestre- Aplicación Coma Rico

Integrantes:
Edgar Meneses
Steven Palacios
Paulette Parra

NRC:
4187

Profesora:
Ing. Margarita Zambrano

Fecha de entrega:
24/02/2017

Sangolquí-Ecuador
CONTENIDO:
1. Objetivos
1.1 General
1.2 Específicos
2. Antecedentes
3. Problema
4. Diseño
5. Código y explicación
6. Implementación
7. Conclusiones

OBJETIVOS:
General:
Crear una aplicación óptima en Java con el uso de Interfaz Gráfica mediante el uso de
clases, objetos, GUI, arrays y con la construcción de un código validado, verificado y
ejecutable para cumplir las especificaciones necesarias y otorgar una solución a la
problemática planteada por el grupo, con el fin de fortalecer conocimientos adquiridos
durante el semestre I 2017 en Programación II.
Específicos:
I. Identificar y desglosar las clases participantes y necesarias que formarán parte
en el programa, demostrando la relación de las mismas con el código UML.
II. Determinar los atributos comprendidos en cada clase y el tipo al que pertenece
cada uno.
III. Construir un código ejecutable sin errores para cumplir las funciones necesarias
en la solución de un problema planteado.
IV. Detallar los métodos primordiales que usamos y cuál fue la función que
determinamos para cada uno de ellos.
V. Exponer nuestro programa o aplicación resultante a nuestros compañeros de
clase demostrando conocimientos aplicados y las validaciones realizadas.
ANTECEDENTES
Muchas veces nos hemos cuestionado el uso de programas pues requieren de un árduo
trabajo tras la construcción de los mismos, pues la interfaz grñafica de usuario
prácticamente se ha ido puliendo con el tiempo hasta nuestros días, mucho tiempo atrás
esto no era real y programar significaba verlo solo desde consola.
En Ecuador, muchos locales de comida y negocios como restaurantes pequeños no
llevaban o siguen sin llevar un registro de clientes, productos y otras variedades, para
dichos lugares basta con un papel en el cual tomar la orden o simplemente la memoria,
prácticamente este ha sido su base para sobrellevar su negocio y lo han permanecido así
por muchos años.
Si nos ponemos a recordar situaciones de salidas con la familia en el momento de
almorzar o cenar en lugares externos al hogar, podríamos habernos percatado de lo difícil
que es adaptar la tecnología con el trabajo de meseros o los dueños de locales de comida
rápida, con el tiempo las normas de venta se han ido reformando en nuestro país con las
leyes Tributarias, tanto así que hace un par de años el SRI reformó sus artículos haciendo
hincapié en el término 10 del Art. 56 de la Ley de Régimen Tributario Interno donde
manifiesta la generación de un comprobante en consumos superiores a $4 sin necesidad
de que se lo solicite previamente por el usuario o cliente, poniendo de manifiesto la
necesidad de nuestro programa a realizar.

DISEÑO DEL PROGRAMA

CÓDIGO DEL PROGRAMA


ADMINISTRADOR

package Clases;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Administrador extends Usuario{

public Administrador(long ci, String nombres, String apellidos, String idUsuario,


String clave, int perfil, Date fechaNac, Date FechaIngreso) {
super(ci, nombres, apellidos, idUsuario, clave, perfil,
fechaNac, FechaIngreso);
}
public long getCi() {
return ci;
}
public void setCi(long ci) {
this.ci = ci;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}

public static Date string_to_Date(String fecha){


SimpleDateFormat formatoDeTexto=new SimpleDateFormat("yyyy/mm/dd");
Date aux=null;
try {
aux=formatoDeTexto.parse(fecha);
} catch (Exception ex) {
System.out.println("");
}
return aux;
}

CAJERO

package Clases;
import java.util.Date;
public class Cajero extends Persona{
private String idUsuario;
private String clave;
private int perfil;
private Date fechaNac;
private Date fechaIngreso;

public Cajero(long ci, String nombres, String apellidos, String idUsuario, String
clave, int perfil, Date fechaNac, Date FechaIngreso) {
super(ci, nombres, apellidos);
this.idUsuario=idUsuario;
this.clave=clave;
this.perfil=perfil;
this.fechaNac=fechaNac;
this.fechaIngreso=FechaIngreso;
}
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public int getPerfil() {
return perfil;
}
public void setPerfil(int perfil) {
this.perfil = perfil;
}
public Date getFechaNac() {
return fechaNac;
}
public void setFechaNac(Date fechaNac) {
this.fechaNac = fechaNac;
}
public Date getFechaIngreso() {
return fechaIngreso;
}

public void setFechaIngreso(Date fechaIngreso) {


this.fechaIngreso = fechaIngreso;
}
@Override
public long getCi() {
return ci;
}
@Override
public void setCi(long ci) {
this.ci = ci;
}
@Override
public String getNombres() {
return nombres;
}
@Override
public void setNombres(String nombres) {
this.nombres = nombres;
}
@Override
public String getApellidos() {
return apellidos;
}
@Override
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
}

CLIENTE

package Clases;
public class Cliente extends Persona{
private String direccion;
private String telefono;

public Cliente(long ci, String nombres, String apellidos,


String direccion, String telefono) {
super(ci, nombres, apellidos);
this.direccion=direccion;
this.telefono=telefono;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
@Override
public long getCi() {
return ci;
}
@Override
public void setCi(long ci) {
this.ci = ci;
}
@Override
public String getNombres() {
return nombres;
}
@Override
public void setNombres(String nombres) {
this.nombres = nombres;
}
@Override
public String getApellidos() {
return apellidos;
}
@Override
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
//método para validar cédula
public boolean validarCedula(long a){
boolean bandera=true;
int CI[]=new int[10],i=9,par=0, impar=0,mul;
int total,res;
long ced,coc;
ced=a;
CI[i]=(int)ced%10;
ced=ced/10;
do{
i--;
coc=ced/10;
CI[i]=(int)ced%10;
ced=coc;
}while(coc!=0);
for(i=0;i<9;i+=2){
mul=CI[i]*2;
if(mul>9){
mul-=9;
}
par+=mul;
}
for(int j=1;j<8;j+=2){
impar+=CI[j];
}
total=par+impar;
res=10-(total%10);
if(res==10){
res=0;
}
if(res==CI[9]){
bandera=true;
}else{
bandera=false;
}
return bandera;
}
@Override
public String toString() {
return nombres + "|" +
apellidos + "|"+
ci + "|" +
direccion + "|" +
telefono;
}
}

FACTURA

package Clases;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class Factura {


private int numeroFac;
private Cliente cliente;
private Date fecha;
private Mesero mesero;
private ArrayList<Producto> misProductos = new ArrayList<>();

public Factura(int numeroFac, Cliente cliente, Date fecha,


Mesero mesero, ArrayList<Producto> misProductos) {
this.numeroFac = numeroFac;
this.cliente = cliente;
this.fecha = fecha;
this.mesero=mesero;
this.misProductos=misProductos;
}
public int getNumeroFac() {
return numeroFac;
}
public void setNumeroFac(int numeroFac) {
this.numeroFac = numeroFac;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Mesero getMesero() {
return mesero;
}
public void setMesero(Mesero mesero) {
this.mesero = mesero;
}
public ArrayList<Producto> getMisProductos() {
return misProductos;
}
public void setMisProductos(ArrayList<Producto> misProductos) {
this.misProductos = misProductos;
}
@Override
public String toString() {
return numeroFac + "|" +
formatDate(fecha) + "|" +"\n"+
cliente.toString( )+"|"+"\n"+
misProductos.toString( )+"|"+"\n"+
mesero.getNombres( );
//aqui hay error
}
private String formatDate (Date fecha){
SimpleDateFormat formatodeltexto=new SimpleDateFormat("dd/MM/yyyy");
return formatodeltexto.format(fecha);
}
}

MESA

package Clases;
public class Mesa {
private int numero;
private int capacidad;

public Mesa(int numero, int capacidad) {


this.numero = numero;
this.capacidad = capacidad;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public int getCapacidad() {
return capacidad;
}
public void setCapacidad(int capacidad) {
this.capacidad = capacidad;
}
}

MESERO

package Clases;
import java.util.Date;
public class Mesero extends Persona{
private String idUsuario;
private String clave;
private int perfil;
private Date fechaNac;
private Date fechaIngreso;

public Mesero(long ci, String nombres, String apellidos,


String idUsuario, String clave, int perfil, Date fechaNac,
Date FechaIngreso) {
super(ci, nombres, apellidos);
this.idUsuario=idUsuario;
this.clave=clave;
this.perfil=perfil;
this.fechaNac=fechaNac;
this.fechaIngreso=FechaIngreso;
}
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public int getPerfil() {
return perfil;
}
public void setPerfil(int perfil) {
this.perfil = perfil;
}
public Date getFechaNac() {
return fechaNac;
}
public void setFechaNac(Date fechaNac) {
this.fechaNac = fechaNac;
}
public Date getFechaIngreso() {
return fechaIngreso;
}
public void setFechaIngreso(Date fechaIngreso) {
this.fechaIngreso = fechaIngreso;
}
@Override
public long getCi() {
return ci;
}
@Override
public void setCi(long ci) {
this.ci = ci;
}
@Override
public String getNombres() {
return nombres;
}
@Override
public void setNombres(String nombres) {
this.nombres = nombres;
}
@Override
public String getApellidos() {
return apellidos;
}
@Override
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
@Override
public String toString() {
return "Mesero{" + "idUsuario=" + idUsuario + ", clave=" + clave + ", perfil=" +
perfil + ", fechaNac=" + fechaNac + ", fechaIngreso=" + fechaIngreso + '}';
}
}

PERSONA

package Clases;
public class Persona {
protected long ci;
protected String nombres, apellidos;

public Persona(long ci, String nombres, String apellidos) {


this.ci = ci;
this.nombres = nombres;
this.apellidos = apellidos;
}
public long getCi() {
return ci;
}
public void setCi(long ci) {
this.ci = ci;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
@Override
public String toString() {
return ci + "|" + nombres + "|" +apellidos + "|";
}
}

PRODUCTO

package Clases;
public class Producto {
//Atributos
private String idProducto;
private String descripcion;
private float precio;
private String nota;
private int categoria, stock;
//constructor
public Producto(String idProducto, String descripcion, float precio, String nota, int
categoria, int stock) {
this.idProducto = idProducto;
this.descripcion = descripcion;
this.precio = precio;
this.nota = nota;
this.categoria = categoria;
this.stock = stock;
}
//validar un precio
public int validarPrecio(String valor){
String a;
try {
a=valor;
precio=Float.parseFloat(a);
if(precio<=0){
return -1;
}else{
return 0;
}
} catch (Exception e) {
return 1;
}
}
//validar cantidad sea un entero
public boolean validarcantidad(String valor){
String a;
try {
a=valor;
precio=Integer.parseInt(a);
return true;
} catch (Exception e) {
return false;
}
}
//get y set
public String getIdProducto() {
return idProducto;
}
public void setIdProducto(String idProducto) {
this.idProducto = idProducto;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public float getPrecio() {
return precio;
}
public void setPrecio(float precio) {
this.precio = precio;
}
public String getNota() {
return nota;
}
public void setNota(String nota) {
this.nota = nota;
}
public int getCategoria() {
return categoria;
}
public void setCategoria(int categoria) {
this.categoria = categoria;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
@Override
public String toString() {
return idProducto +"|"+
descripcion + "|" +
precio + "|" +
nota + "|" +
categoria + "|" +
stock; }
}

USUARIO

package Clases;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Usuario extends Persona{
private String idUsuario;
private String clave;
private int perfil;
private Date fechaNac;
private Date fechaIngreso;

public Usuario(long ci, String nombres, String apellidos,


String idUsuario, String clave, int perfil, Date fechaNac, Date FechaIngreso) {
super(ci, nombres, apellidos);
this.idUsuario=idUsuario;
this.clave=clave;
this.perfil=perfil;
this.fechaNac=fechaNac;
this.fechaIngreso=FechaIngreso;
}
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public int getPerfil() {
return perfil;
}
public void setPerfil(int perfil) {
this.perfil = perfil;
}
public Date getFechaNac() {
return fechaNac;
}
public void setFechaNac(Date fechaNac) {
this.fechaNac = fechaNac;
}
public Date getFechaIngreso() {
return fechaIngreso;
}
public void setFechaIngreso(Date fechaIngreso) {
this.fechaIngreso = fechaIngreso;
}
@Override
public long getCi() {
return ci;
}
@Override
public void setCi(long ci) {
this.ci = ci;
}
@Override
public String getNombres() {
return nombres;
}
@Override
public void setNombres(String nombres) {
this.nombres = nombres;
}
@Override
public String getApellidos() {
return apellidos;
}
@Override
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}

public int cambioClave(String antiguo,


String nuevo, String confirmacion){
if(!antiguo.equals(clave)){
return -1;
}else{
if(!nuevo.equals(confirmacion)){
return 1;
}else{
clave=nuevo;
return 0;
}
}
}
//método para vlidar cédula
public boolean validarCedula(long a){
boolean bandera=true;
int CI[]=new int[10],i=9,par=0, impar=0,mul;
int total,res;
long ced,coc;
ced=a;
CI[i]=(int)ced%10;
ced=ced/10;
do{
i--;
coc=ced/10;
CI[i]=(int)ced%10;
ced=coc;
}while(coc!=0);
for(i=0;i<9;i+=2){
mul=CI[i]*2;
if(mul>9){
mul-=9;
}
par+=mul;
}
for(int j=1;j<8;j+=2){
impar+=CI[j];
}
total=par+impar;
res=10-(total%10);
if(res==10){
res=0;
}
if(res==CI[9]){
bandera=true;
}else{
bandera=false;
}
return bandera;
}
@Override
public String toString() {
return idUsuario + "|" +
nombres + "|" +
apellidos + "|"+
ci + "|" +
clave + "|" +
perfil + "|" +
formatDate(fechaNac) + "|" +
formatDate(fechaIngreso) + "|";
}
private String formatDate (Date fecha){
SimpleDateFormat formatodeltexto=new SimpleDateFormat("dd/MM/yyyy");
return formatodeltexto.format(fecha);
}
}
EN EL MAIN

package Clases;
import Formularios.frmEntrada;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Proyecto_Factura_Inge {

private static ArrayList<Cliente> misClientes = new ArrayList<>();


private static ArrayList<Usuario> misUsuarios = new ArrayList<>();
private static ArrayList<Producto> misProductos = new ArrayList<>();

public static void main(String[] args) {


//métodos privados para cargar los usuarios y productos
//desde un archivo .txt
cargarUsuario();
cargarCliente();
cargarProducto();
//llamada del formulario de entrada
frmEntrada entrada = new frmEntrada();
entrada.setUsuarios(misUsuarios);
entrada.setClientes(misClientes);
entrada.setProductos(misProductos);
entrada.setLocationRelativeTo(null);
entrada.setVisible(true);

}
private static void cargarUsuario() {
File archivo = null;
FileReader fr = null;
BufferedReader bf = null;

try {
//para leer el archivo
archivo = new File("DatosSistema/Usuarios.txt");
fr = new FileReader(archivo);
bf = new BufferedReader(fr);
//para guardar los datos en variables de usuario
int pos;
String aux, linea;
String ci;
String idUsuario;
String nombres;
String apellidos;
String clave;
int perfil;
Date fechaNac;
Date fechaIngreso;

while ((linea = bf.readLine()) != null) {


//captura ci
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
apellidos = aux;
linea = linea.substring(pos + 1);
//captura nombres
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
idUsuario = aux;
linea = linea.substring(pos + 1);

//captura apellidos
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
nombres = aux;
linea = linea.substring(pos + 1);

//captura idUsuario
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
ci = aux;
linea = linea.substring(pos + 1);

//captura clave
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
clave = aux;
linea = linea.substring(pos + 1);

//captura perfil
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
perfil = new Integer(aux);
linea = linea.substring(pos + 1);
//captura fecha de nacimiento e ingreso
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
fechaNac = StringDate(aux);
linea = linea.substring(pos + 1);
fechaIngreso = StringDate(linea);

Usuario miUsuario = new Usuario(


Long.parseLong(ci),
idUsuario,
nombres,
apellidos,
clave,
perfil,
fechaNac,
fechaIngreso);

misUsuarios.add(miUsuario);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
private static void cargarCliente() {
File archivo = null;
FileReader fr = null;
BufferedReader bf = null;

try {
//para leer el archivo
archivo = new File("DatosSistema/Clientes.txt");
fr = new FileReader(archivo);
bf = new BufferedReader(fr);
//para guardar los datos en variables de cleinte
int pos;
String aux, linea;
String ci;
String idCliente;
String nombres;
String apellidos;
String direccion;
String telefono;

while ((linea = bf.readLine()) != null) {


pos = linea.indexOf('|');
aux = linea.substring(0, pos);
nombres = aux;
linea = linea.substring(pos + 1);

//captura apellidos
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
apellidos = aux;
linea = linea.substring(pos + 1);

//captura ci
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
ci = aux;
linea = linea.substring(pos + 1);
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
direccion = aux;
linea = linea.substring(pos + 1);
telefono = linea;

Cliente miCliente = new Cliente(


Long.parseLong(ci),
nombres,
apellidos,
direccion,
telefono);

misClientes.add(miCliente);

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
private static void cargarProducto() {
File archivo = null;
FileReader fr = null;
BufferedReader bf = null;

try {
//para leer el archivo
archivo = new File("DatosSistema/Productos.txt");
fr = new FileReader(archivo);
bf = new BufferedReader(fr);
//para guardar los datos en variables de producto
int pos;
String aux, linea;
String idProducto;
String descripcion;
float precio;
String nota;
int categoria;
int stock;

while ((linea = bf.readLine()) != null) {


//captura idProducto
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
idProducto = aux;
linea = linea.substring(pos + 1);

//captura descripcion
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
descripcion = aux;
linea = linea.substring(pos + 1);

//captura precio
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
precio = Float.parseFloat(aux);
linea = linea.substring(pos + 1);

//captura nota
pos = linea.indexOf('|');
aux = linea.substring(0, pos);
nota = aux;
linea = linea.substring(pos + 1);

//captura categoria y stock


pos = linea.indexOf('|');
aux = linea.substring(0, pos);
categoria = new Integer(aux);
linea = linea.substring(pos + 1);
stock = new Integer(linea);

Producto miProducto = new Producto(


idProducto,
descripcion,
precio,
nota,
categoria,
stock);
misProductos.add(miProducto);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
//Método para convertir String a fecha
public static Date StringDate(String fecha) {
SimpleDateFormat formaDelTexto = new SimpleDateFormat("dd/MM/yyyy");
Date aux = null;
try {
aux = formaDelTexto.parse(fecha);
} catch (Exception ex) {

}
return aux;
}
//Método para cambiar el formato fecha en String
public static String formatDate(Date fecha) {
SimpleDateFormat formatodeltexto = new SimpleDateFormat("dd/MM/yyyy");
return formatodeltexto.format(fecha);
}
}

EN EL FRAME
frmEntrada
Design

Source

package Formularios;
import Clases.Cliente;
import Clases.Producto;
import Clases.Usuario;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class frmEntrada extends javax.swing.JFrame {
private ArrayList<Usuario> misUsuarios = new ArrayList<>();
private ArrayList<Cliente> misClientes = new ArrayList<>();
private ArrayList<Producto> misProductos = new ArrayList<>();
public void setProductos(ArrayList<Producto> misProductos) {
this.misProductos = misProductos;
}
public void setUsuarios(ArrayList<Usuario> misUsuarios) {
this.misUsuarios = misUsuarios;
}

public void setClientes(ArrayList<Cliente> misClientes) {


this.misClientes = misClientes;
}
public frmEntrada() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jlabel1 = new javax.swing.JLabel();
txtUsuario = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtClave = new javax.swing.JPasswordField();
btnAceptar = new javax.swing.JButton();
btnCancelar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Ingreso al sistema");
setResizable(false);
jlabel1.setText("Usuario:");
jLabel2.setText("Clave:");
btnAceptar.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/Imagenes/Accept.png"))); // NOI18N
btnAceptar.setText("Aceptar");
btnAceptar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnAceptarMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnAceptarMouseEntered(evt);
}
});
btnAceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAceptarActionPerformed(evt);
}
});
btnAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
btnAceptarKeyPressed(evt);
}
});
btnCancelar.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/Imagenes/Cancel.png"))); // NOI18N
btnCancelar.setText("Cancelar");
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
btnCancelar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
btnCancelarKeyPressed(evt);
}
});
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/Imagenes/logo .png"))); // NOI18N
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING
)
.addGroup(layout.createSequentialGroup()
.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING
)
.addComponent(jLabel2,
javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jlabel1,
javax.swing.GroupLayout.Alignment.TRAILING))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING
)
.addComponent(txtUsuario,
javax.swing.GroupLayout.PREFERRED_SIZE, 158,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtClave,
javax.swing.GroupLayout.PREFERRED_SIZE, 158,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(btnAceptar)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCancelar)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILIN
G) .addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN
E)
.addComponent(jlabel1)
.addComponent(txtUsuario,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN
E)
.addComponent(jLabel2)
.addComponent(txtClave,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN
E)
.addComponent(btnAceptar)
.addComponent(btnCancelar))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
pack();
}// </editor-fold>

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {


System.exit(0);
}

private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {


String clave = new String(txtClave.getPassword());
int a = 0;
for (int i = 0; i < misUsuarios.size(); i++) {
if (txtUsuario.getText().equals(misUsuarios.get(i).getIdUsuario())
&& clave.equals(misUsuarios.get(i).getClave())) {
frmPrincipal principal = new frmPrincipal();
principal.setUsuarios(misUsuarios);
principal.setClientes(misClientes);
principal.setProductos(misProductos);
principal.setPerfil(misUsuarios.get(i).getPerfil());
principal.setClave(misUsuarios.get(i).getClave());
principal.setID(misUsuarios.get(i).getIdUsuario());
principal.setLocationRelativeTo(null);
principal.setVisible(true);
setVisible(false);
a = 1;
}
}
if (a == 0) {
JOptionPane.showMessageDialog(rootPane, "Usuario o clave incorrecto");
txtUsuario.setText("");
txtClave.setText("");
txtUsuario.requestFocusInWindow();
return;
}
}
private void btnAceptarMouseEntered(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnAceptarMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnAceptarKeyPressed(java.awt.event.KeyEvent evt) {

}
private void btnCancelarKeyPressed(java.awt.event.KeyEvent evt) {
// this.dispose();
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look
and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(frmEntrada.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(frmEntrada.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(frmEntrada.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(frmEntrada.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmEntrada().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAceptar;
private javax.swing.JButton btnCancelar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jlabel1;
private javax.swing.JPasswordField txtClave;
private javax.swing.JTextField txtUsuario;
// End of variables declaration
}

frmPrincipal
Design

Source
/*MUESTRA EL SALON DEL RESTAURANTE*/
package Formularios;
import Clases.Cliente;
import Clases.DesktopConFondo;
import Clases.Producto;
import Clases.Usuario;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
*
* @author EDGAR MENESES
*/
public class frmPrincipal extends javax.swing.JFrame {
private int perfil;
private String clave,id;
private ArrayList<Usuario> misUsuarios = new ArrayList<>();
private ArrayList<Cliente> misClientes = new ArrayList<>();
private ArrayList<Producto> misProductos=new ArrayList<>();
private frmPedido pedido[]=new frmPedido[15];

public void setProductos(ArrayList<Producto> misProductos) {


this.misProductos = misProductos;
}
public void setUsuarios(ArrayList<Usuario> misUsuarios) {
this.misUsuarios = misUsuarios;
}
public void setClientes(ArrayList<Cliente> misClientes) {
this.misClientes = misClientes;
}
public void setPerfil(int perfil){
this.perfil=perfil;
}
public void setClave(String clave){
this.clave=clave;
}
public void setID(String id){
this.id=id;
}
public frmPrincipal() {
for (int i = 0; i < 15; i++) {
pedido[i]=new frmPedido();
}
initComponents();
}
public void abrirMesas(){
for (int i = 0; i < 15; i++) {
dpnEscritorio.add(pedido[i]);
}
}
@SuppressWarnings("unchecked")
Generated Code
private void mnuArchivoClientesActionPerformed(java.awt.event.ActionEvent evt) {
frmClientes cliente =new frmClientes();
cliente.setClientes(misClientes);
dpnEscritorio.add(cliente);
cliente.show();
}
private void mnuArchivoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {
frmUsuarios usuarios =new frmUsuarios();
usuarios.setUsuarios(misUsuarios);
dpnEscritorio.add(usuarios);
usuarios.show();
}

private void mnuArchivoCAmbioClaveActionPerformed(java.awt.event.ActionEvent


evt) {
frmCambio nuevo=new frmCambio(this, rootPaneCheckingEnabled);
nuevo.setID(id);
nuevo.setUsuarios(misUsuarios);
nuevo.setClave(clave);
nuevo.setLocationRelativeTo(this);
nuevo.setVisible(true);

private void
mnuArchivoCambioUsuarioActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
frmEntrada milogin=new frmEntrada();
milogin.setUsuarios(misUsuarios);
milogin.setClientes(misClientes);
milogin.setProductos(misProductos);
milogin.setLocationRelativeTo(null);
milogin.setVisible(true);
}

private void mnuArchivoSalirActionPerformed(java.awt.event.ActionEvent evt) {


guardarTodo();
System.exit(0);
}

private void mnuAlmacenProductosActionPerformed(java.awt.event.ActionEvent


evt) {
frmProductos productos =new frmProductos();
productos.setProductos(misProductos);
dpnEscritorio.add(productos);
productos.show();

private void mnuAlmacenNuevaFacturaActionPerformed(java.awt.event.ActionEvent


evt) {

private void mnuAyudaAcercadeActionPerformed(java.awt.event.ActionEvent evt) {


frmAcercaDe inf=new frmAcercaDe();
dpnEscritorio.add(inf);
inf.show();
}

private void formWindowOpened(java.awt.event.WindowEvent evt) {


//para poner la imagen de fondo
((DesktopConFondo) dpnEscritorio).setImagen("/Imagenes/escritorio.jpg");
abrirMesas();
//// //EStablece permisos
switch (perfil){
case 1:
break;
case 2:
mnuArchivoUsuario.setEnabled(false);
mnuArchivoClientes.setEnabled(false);
mnuAlmacenProductos.setEnabled(false);
break;
case 3:
mnuArchivoUsuario.setEnabled(false);
mnuArchivoClientes.setEnabled(false);
mnuAlmacenProductos.setEnabled(false);
break;
}
}

private void btnMesa1ActionPerformed(java.awt.event.ActionEvent evt) {


pedido[0].setMesa(1);
pedido[0].setUsuarios(misUsuarios);
pedido[0].setProductos(misProductos);
pedido[0].setClientes(misClientes);
pedido[0].show();
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look
and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.
Level.SEVERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.
Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.
Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.
Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmPrincipal().setVisible(true);
}
});
}

// guarda todos los datos de usuario y productos


public void guardarTodo(){
guardarUsuario();
guardarClientes();
guardarProducto();
}

//Guardar datos de usuarios en archivos planos


private void guardarUsuario() {
FileWriter fw=null;
PrintWriter pw=null;

try {
fw=new FileWriter("DatosSistema/Usuarios.txt");
pw=new PrintWriter(fw);

for (int i = 0; i < misUsuarios.size(); i++) {


pw.println(misUsuarios.get(i).toString());
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fw!=null){
fw.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
//Guardar datos de clientes en archivos planos
private void guardarClientes() {
FileWriter fw=null;
PrintWriter pw=null;
try {
fw=new FileWriter("DatosSistema/Clientes.txt");
pw=new PrintWriter(fw);
for (int i = 0; i < misClientes.size(); i++) {
pw.println(misClientes.get(i).toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fw!=null){
fw.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
//Guardar datos de productos en archivos planos
private void guardarProducto() {
FileWriter fw=null;
PrintWriter pw=null;

try {
fw=new FileWriter("DatosSistema/Productos.txt");
pw=new PrintWriter(fw);

for (int i = 0; i < misProductos.size(); i++) {


pw.println(misProductos.get(i).toString());
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fw!=null){
fw.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
// Variables declaration - do not modify
private javax.swing.JMenuBar Ayuda;
private javax.swing.JButton btnMesa1;
private javax.swing.JButton btnMesa10;
private javax.swing.JButton btnMesa11;
private javax.swing.JButton btnMesa12;
private javax.swing.JButton btnMesa13;
private javax.swing.JButton btnMesa14;
private javax.swing.JButton btnMesa15;
private javax.swing.JButton btnMesa2;
private javax.swing.JButton btnMesa3;
private javax.swing.JButton btnMesa4;
private javax.swing.JButton btnMesa5;
private javax.swing.JButton btnMesa6;
private javax.swing.JButton btnMesa7;
private javax.swing.JButton btnMesa8;
private javax.swing.JButton btnMesa9;
private javax.swing.JDesktopPane dpnEscritorio;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator2;
private javax.swing.JPopupMenu.Separator jSeparator3;
private javax.swing.JMenuItem mnuAlmacenNuevaFactura;
private javax.swing.JMenuItem mnuAlmacenProductos;
private javax.swing.JMenu mnuArchivo;
private javax.swing.JMenuItem mnuArchivoCAmbioClave;
private javax.swing.JMenuItem mnuArchivoCambioUsuario;
private javax.swing.JMenuItem mnuArchivoClientes;
private javax.swing.JMenuItem mnuArchivoSalir;
private javax.swing.JMenuItem mnuArchivoUsuario;
private javax.swing.JMenu mnuAyuda;
private javax.swing.JMenuItem mnuAyudaAcercade;
private javax.swing.JMenu mnuMovimientos;
// End of variables declaration
}

frmClientes
Design
Source

package Formularios;
import Clases.Cliente;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class frmClientes extends javax.swing.JInternalFrame {


private int usuAct ;
boolean nuevo;
private DefaultTableModel miTabla;
private ArrayList<Cliente> misClientes = new ArrayList<>();
public void setClientes(ArrayList<Cliente> misClientes) {
this.misClientes = misClientes;
}
public frmClientes() {
initComponents();
usuAct=0;
nuevo=false;
}
@SuppressWarnings("unchecked")
Generated Code
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {
//Validación de campos vacios

if (txtNombres.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el nombre");
txtNombres.requestFocusInWindow();
return;
}
if (txtApellidos.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el apellido");
txtApellidos.requestFocusInWindow();
return;
}
if (txtCedula.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el número de
cédula");
txtCedula.requestFocusInWindow();
return;
}

if(!esLong(txtCedula.getText())){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar una cadena de
números");
txtCedula.setText(null);
txtCedula.requestFocusInWindow();
return;
}

if
(misClientes.get(0).validarCedula(Long.parseLong(txtCedula.getText()))==false){
JOptionPane.showMessageDialog(rootPane, "Número de cédula incorrecto");
txtCedula.setText(null);
txtCedula.requestFocusInWindow();
return;
}
if (txtDireccion.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar una dirección");
txtDireccion.requestFocusInWindow();
return;
}
if (txtTelefono.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un número de
teléfono");
txtTelefono.requestFocusInWindow();
return;
}
if(!esLong(txtTelefono.getText())){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar una cadena de
números");
txtTelefono.setText(null);
txtTelefono.requestFocusInWindow();
return;
}
//Validación que el cliente no exista
int pos = posicionCliiente(txtCedula.getText());
if (nuevo) {
if (pos != -1) {
JOptionPane.showMessageDialog(rootPane, "Cliente ya existe");
txtCedula.requestFocusInWindow();
return;
}
} else if (pos == -1) {
JOptionPane.showMessageDialog(rootPane, "Cliente no existe");
txtCedula.requestFocusInWindow();
return;
}

//Creamos el objeto usuario y los agregamos a datos


long cedula;
cedula=Long.parseLong(txtCedula.getText());
Cliente miCliente = new Cliente(
cedula,
txtNombres.getText(),
txtApellidos.getText(),
txtDireccion.getText(),
txtTelefono.getText());
String mns;
if (nuevo) {
misClientes.add(miCliente);
JOptionPane.showMessageDialog(rootPane, "Cliente agregado correctamente");
} else {
mns=modificarCliente(miCliente, pos);
JOptionPane.showMessageDialog(rootPane, mns);
}
//habilitar botones
btnPrimero.setEnabled(true);
btnAnterior.setEnabled(true);
btnSiguiente.setEnabled(true);
btnUltimo.setEnabled(true);
btnNuevo.setEnabled(true);
btnModificar.setEnabled(true);
btnBorrar.setEnabled(true);
btnBuscar.setEnabled(true);
btnGuardar.setEnabled(false);
btnCancelar.setEnabled(false);

//Deshabilita los campos


txtNombres.setEnabled(false);
txtApellidos.setEnabled(false);
txtCedula.setEnabled(false);
txtDireccion.setEnabled(false);
txtTelefono.setEnabled(false);
//actualizamos tabla
llenarTabla();
}

private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {


String cliente = JOptionPane.showInputDialog("Ingrese la cédula del cliente");
if (cliente.equals("")) {
return;
}
int pos = posicionCliiente(cliente);
if (pos == -1) {
JOptionPane.showMessageDialog(rootPane, "El cliente no existe");
return;
}
usuAct = pos;
mostrarRegistro();
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
//Habilita los botones
btnPrimero.setEnabled(true);
btnAnterior.setEnabled(true);
btnSiguiente.setEnabled(true);
btnUltimo.setEnabled(true);
btnNuevo.setEnabled(true);
btnModificar.setEnabled(true);
btnBorrar.setEnabled(true);
btnBuscar.setEnabled(true);
btnGuardar.setEnabled(false);
btnCancelar.setEnabled(false);

//Deshabilita los campos


txtNombres.setEnabled(false);
txtApellidos.setEnabled(false);
txtCedula.setEnabled(false);
txtDireccion.setEnabled(false);
txtTelefono.setEnabled(false);

usuAct = 0;
mostrarRegistro();
}
private void btnPrimeroActionPerformed(java.awt.event.ActionEvent evt) {
usuAct = 0;
mostrarRegistro();
}

private void btnUltimoActionPerformed(java.awt.event.ActionEvent evt) {


usuAct = misClientes.size()-1;
mostrarRegistro();
}

private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {


usuAct--;
if (usuAct == -1) {
usuAct = misClientes.size()- 1;
}
mostrarRegistro();
}

private void btnSiguienteActionPerformed(java.awt.event.ActionEvent evt) {


usuAct++;
if (usuAct == misClientes.size()) {
usuAct = 0;
}
mostrarRegistro();
}
private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {
//Habilitar deshabilitar botones
btnPrimero.setEnabled(false);
btnAnterior.setEnabled(false);
btnSiguiente.setEnabled(false);
btnUltimo.setEnabled(false);
btnNuevo.setEnabled(false);
btnModificar.setEnabled(false);
btnBorrar.setEnabled(false);
btnBuscar.setEnabled(false);
btnGuardar.setEnabled(true);
btnCancelar.setEnabled(true);

//Habilita los campos


txtNombres.setEnabled(true);
txtApellidos.setEnabled(true);
txtCedula.setEnabled(true);
txtDireccion.setEnabled(true);
txtTelefono.setEnabled(true);

//Limpiar Campos
txtNombres.setText(null);
txtApellidos.setText(null);
txtCedula.setText(null);
txtDireccion.setText(null);
txtTelefono.setText(null);
//Activar el flag de registro nuevo
nuevo = true;

//Damos Foco al campo ID


txtCedula.requestFocusInWindow();
}

private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {


int rpta = JOptionPane.showConfirmDialog(rootPane, "¿Está seguro que desea
borrar el registro?");
if (rpta != 0) {
return;
}
misClientes.remove(usuAct);

usuAct = 0;
mostrarRegistro();

//actualizamos tabla
llenarTabla();
}
private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {
//Habilita los botones
btnPrimero.setEnabled(false);
btnAnterior.setEnabled(false);
btnSiguiente.setEnabled(false);
btnUltimo.setEnabled(false);
btnNuevo.setEnabled(false);
btnModificar.setEnabled(false);
btnBorrar.setEnabled(false);
btnBuscar.setEnabled(false);
btnGuardar.setEnabled(true);
btnCancelar.setEnabled(true);
//Habilita los campos
txtNombres.setEnabled(true);
txtApellidos.setEnabled(true);
txtCedula.setEnabled(true);
txtDireccion.setEnabled(true);
txtTelefono.setEnabled(true);
//Desactivar el flag de registro nuevo
nuevo = false;
//Damos Foco al campo ID
txtNombres.requestFocusInWindow();
}
private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
mostrarRegistro();
llenarTabla();
}
private void mostrarRegistro() {
txtNombres.setText(misClientes.get(usuAct).getNombres());
txtApellidos.setText(misClientes.get(usuAct).getApellidos());
txtDireccion.setText(misClientes.get(usuAct).getDireccion());
txtTelefono.setText(misClientes.get(usuAct).getTelefono());
txtCedula.setText(""+misClientes.get(usuAct).getCi());
}
private void llenarTabla() {
//titulos de la tabla
String titulos[] = {"Cédula", "Nombres", "Apellidos", "Dirección", "Teléfono"};
//registramos el número de columnas
String registro[] = new String[5];
//pasamos los titulos a la tabla
miTabla = new DefaultTableModel(null, titulos);
for (int i = 0; i < misClientes.size(); i++) {
registro[0] = ""+misClientes.get(i).getCi();
registro[1] = misClientes.get(i).getNombres();
registro[2] = misClientes.get(i).getApellidos();
registro[3] = misClientes.get(i).getDireccion();
registro[4] = misClientes.get(i).getTelefono();
miTabla.addRow(registro);
}
tblTablaClientes.setModel(miTabla);
}
//devuelve la posicion en el arreglo de usuarios
public int posicionCliiente(String cliente){
for(int i=0;i<misClientes.size(); i++){
if (misClientes.get(i).getCi()==(Long.parseLong(cliente))){
return i;
}
}
return -1;
}
//devuelve un usuario modificado
public String modificarCliente(Cliente miCliente, int posicion){
misClientes.get(posicion).setNombres(miCliente.getNombres());
misClientes.get(posicion).setApellidos(miCliente.getApellidos());
misClientes.get(posicion).setCi(miCliente.getCi());
misClientes.get(posicion).setDireccion(miCliente.getDireccion());
misClientes.get(posicion).setTelefono(miCliente.getTelefono());
return "Usuario modificado correctamente";
}
//para validar que la cedula sea un long
public boolean esLong(String cadena){
try{
Long.parseLong(cadena);
return true;
}catch(NumberFormatException ex){
return false;
}
}
// Variables declaration - do not modify
private javax.swing.JButton btnAnterior;
private javax.swing.JButton btnBorrar;
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnGuardar;
private javax.swing.JButton btnModificar;
private javax.swing.JButton btnNuevo;
private javax.swing.JButton btnPrimero;
private javax.swing.JButton btnSiguiente;
private javax.swing.JButton btnUltimo;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblTablaClientes;
private javax.swing.JTextField txtApellidos;
private javax.swing.JTextField txtCedula;
private javax.swing.JTextField txtDireccion;
private javax.swing.JTextField txtNombres;
private javax.swing.JTextField txtTelefono;
// End of variables declaration
}

frmUsuarios
Design
Source

package Formularios;
import Clases.Usuario;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import sun.util.logging.resources.logging;
public class frmUsuarios extends javax.swing.JInternalFrame {

private int usuAct ;


boolean nuevo;
private DefaultTableModel miTabla;
ArrayList<Usuario> misUsuarios = new ArrayList<>();
public void setUsuarios(ArrayList<Usuario> misUsuarios) {
this.misUsuarios = misUsuarios;
}
public frmUsuarios() {
initComponents();
usuAct=0;
nuevo=false;
}
@SuppressWarnings("unchecked")
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {
//Validación de campos vacios
if (txtIDUsuario.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe digitar un Id");
txtIDUsuario.requestFocusInWindow();
return;
}
if (txtNombres.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el nombre");
txtNombres.requestFocusInWindow();
return;
}
if (txtApellidos.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el apellido");
txtApellidos.requestFocusInWindow();
return;
}
if (txtCedula.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el número de
cédula");
txtCedula.requestFocusInWindow();
return;
}
if(!esLong(txtCedula.getText())){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar una cadena de
números");
txtCedula.setText(null);
txtCedula.requestFocusInWindow();
return;
}
if
(misUsuarios.get(0).validarCedula(Long.parseLong(txtCedula.getText()))==false){
JOptionPane.showMessageDialog(rootPane, "Número de cédula incorrecto");
txtCedula.setText(null);
txtCedula.requestFocusInWindow();
return;
}
if (cmbPerfil.getSelectedIndex() == 0) {
JOptionPane.showMessageDialog(rootPane, "Debe seleccionar un perfil");
cmbPerfil.requestFocusInWindow();
return;
}
String clave = new String(txtClave.getPassword());
String confirmacion = new String(txtConfirmacion.getPassword());
if (clave.equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe digitar una clave");
txtClave.requestFocusInWindow();
return;
}
if (confirmacion.equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe confirmar su clave");
txtClave.setText(null);
txtConfirmacion.setText(null);
txtConfirmacion.requestFocusInWindow();
return;
}
//validacion de clave y confirmación
if (!clave.equals(confirmacion)) {
JOptionPane.showMessageDialog(rootPane, "La clave y la confirmacón no
coinciden");
txtConfirmacion.setText(null);
txtClave.setText(null);
txtClave.requestFocusInWindow();
return;
}
//validación de fechas
if (txtFechaNac.getDate().equals(txtFechaIngreso.getDate())) {
JOptionPane.showMessageDialog(rootPane,"La fecha de nacimiento "
+ "debe ser anterior a la fecha actual");
txtFechaNac.requestFocusInWindow();
return;
}
if (txtFechaNac.getDate().after(new Date())) {
JOptionPane.showMessageDialog(rootPane, "La fecha de nacimiento "
+ "debe ser anterior a la fecha actual");
txtFechaNac.requestFocusInWindow();
return;
}
//Validación que el usuario no exista
int pos = posicionUsuario(txtIDUsuario.getText());
if (nuevo) {
if (pos != -1) {
JOptionPane.showMessageDialog(rootPane, "Usuario ya existe");
txtIDUsuario.requestFocusInWindow();
return;
}
} else if (pos == -1) {
JOptionPane.showMessageDialog(rootPane, "Usuario no existe");
txtIDUsuario.requestFocusInWindow();
return;
}
//Creamos el objeto usuario y los agregamos a datos
long cedula;
cedula=Long.parseLong(txtCedula.getText());
Usuario miUsuario = new Usuario(cedula,
txtNombres.getText(),
txtApellidos.getText(),
txtIDUsuario.getText(),
clave,
cmbPerfil.getSelectedIndex(),
txtFechaNac.getDate(),
txtFechaIngreso.getDate());
String mns;
if (nuevo) {
misUsuarios.add(miUsuario);
JOptionPane.showMessageDialog(rootPane, "Usuario agregado
correctamente");
} else {
mns=modificarUsuario(miUsuario, pos);
JOptionPane.showMessageDialog(rootPane, mns);
}
//habilitar botones
btnPrimero.setEnabled(true);
btnAnterior.setEnabled(true);
btnSiguiente.setEnabled(true);
btnUltimo.setEnabled(true);
btnNuevo.setEnabled(true);
btnModificar.setEnabled(true);
btnBorrar.setEnabled(true);
btnBuscar.setEnabled(true);
btnGuardar.setEnabled(false);
btnCancelar.setEnabled(false);

//Deshabilita los campos


txtIDUsuario.setEnabled(false);
txtNombres.setEnabled(false);
txtApellidos.setEnabled(false);
txtClave.setEnabled(false);
txtConfirmacion.setEnabled(false);
cmbPerfil.setEnabled(false);
txtFechaNac.setEnabled(false);
txtFechaIngreso.setEnabled(false);
txtCedula.setEnabled(false);
//actualizamos tabla
llenarTabla();
}

private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {


String usuario = JOptionPane.showInputDialog("Ingrese código de usuario");
if (usuario.equals("")) {
return;
}
int pos = posicionUsuario(usuario);
if (pos == -1) {
JOptionPane.showMessageDialog(rootPane, "El usuario no existe");
return;
}
usuAct = pos;
mostrarRegistro();
}
private void cmbPerfilActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
//Habilita los botones
btnPrimero.setEnabled(true);
btnAnterior.setEnabled(true);
btnSiguiente.setEnabled(true);
btnUltimo.setEnabled(true);
btnNuevo.setEnabled(true);
btnModificar.setEnabled(true);
btnBorrar.setEnabled(true);
btnBuscar.setEnabled(true);
btnGuardar.setEnabled(false);
btnCancelar.setEnabled(false);

//Deshabilita los campos


txtIDUsuario.setEnabled(false);
txtNombres.setEnabled(false);
txtApellidos.setEnabled(false);
txtClave.setEnabled(false);
txtConfirmacion.setEnabled(false);
cmbPerfil.setEnabled(false);
txtFechaNac.setEnabled(false);
txtFechaIngreso.setEnabled(false);
txtCedula.setEnabled(false);
usuAct = 0;
mostrarRegistro();
}
private void btnPrimeroActionPerformed(java.awt.event.ActionEvent evt) {
usuAct = 0;
mostrarRegistro();
}
private void btnUltimoActionPerformed(java.awt.event.ActionEvent evt) {
usuAct = misUsuarios.size()-1;
mostrarRegistro();
}
private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {
usuAct--;
if (usuAct == -1) {
usuAct = misUsuarios.size()- 1;
}
mostrarRegistro();
}
private void btnSiguienteActionPerformed(java.awt.event.ActionEvent evt) {
usuAct++;
if (usuAct == misUsuarios.size()) {
usuAct = 0;
}
mostrarRegistro();
}
private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {
//Habilitar deshabilitar botones
btnPrimero.setEnabled(false);
btnAnterior.setEnabled(false);
btnSiguiente.setEnabled(false);
btnUltimo.setEnabled(false);
btnNuevo.setEnabled(false);
btnModificar.setEnabled(false);
btnBorrar.setEnabled(false);
btnBuscar.setEnabled(false);
btnGuardar.setEnabled(true);
btnCancelar.setEnabled(true);

//Habilita los campos


txtIDUsuario.setEnabled(true);
txtNombres.setEnabled(true);
txtApellidos.setEnabled(true);
txtClave.setEnabled(true);
txtConfirmacion.setEnabled(true);
cmbPerfil.setEnabled(true);
cmbPerfil.setSelectedIndex(0);
txtFechaNac.setEnabled(true);
txtFechaIngreso.setEnabled(true);
txtCedula.setEnabled(true);

//Limpiar Campos
txtIDUsuario.setText(null);
txtNombres.setText(null);
txtApellidos.setText(null);
txtClave.setText(null);
txtConfirmacion.setText(null);
txtFechaNac.setDate(new Date());
txtFechaIngreso.setDate(new Date());
txtCedula.setText(null);
//Activar el flag de registro nuevo
nuevo = true;
//Damos Foco al campo ID
txtIDUsuario.requestFocusInWindow();
}
private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {
int rpta = JOptionPane.showConfirmDialog(rootPane, "¿Está seguro que desea
borrar el registro?");
if (rpta != 0) {
return;
}
misUsuarios.remove(usuAct);
usuAct = 0;
mostrarRegistro();
//actualizamos tabla
llenarTabla();
}
private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {
//Habilita los botones
btnPrimero.setEnabled(false);
btnAnterior.setEnabled(false);
btnSiguiente.setEnabled(false);
btnUltimo.setEnabled(false);
btnNuevo.setEnabled(false);
btnModificar.setEnabled(false);
btnBorrar.setEnabled(false);
btnBuscar.setEnabled(false);
btnGuardar.setEnabled(true);
btnCancelar.setEnabled(true);

//Habilita los campos


txtNombres.setEnabled(true);
txtApellidos.setEnabled(true);
txtClave.setEnabled(true);
txtConfirmacion.setEnabled(true);
cmbPerfil.setEnabled(true);
txtFechaNac.setEnabled(true);
txtFechaIngreso.setEnabled(false);
txtCedula.setEnabled(true);
//Desactivar el flag de registro nuevo
nuevo = false;
//Damos Foco al campo ID
txtNombres.requestFocusInWindow();
}
private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
mostrarRegistro();
llenarTabla();
}
private void mostrarRegistro() {
txtIDUsuario.setText(misUsuarios.get(usuAct).getIdUsuario());
txtNombres.setText(misUsuarios.get(usuAct).getNombres());
txtApellidos.setText(misUsuarios.get(usuAct).getApellidos());
txtClave.setText(misUsuarios.get(usuAct).getClave());
txtConfirmacion.setText(misUsuarios.get(usuAct).getClave());
cmbPerfil.setSelectedIndex(misUsuarios.get(usuAct).getPerfil());
txtFechaNac.setDate(misUsuarios.get(usuAct).getFechaNac());
txtFechaIngreso.setDate(misUsuarios.get(usuAct).getFechaIngreso());
txtCedula.setText(""+misUsuarios.get(usuAct).getCi());

private void llenarTabla() {


//titulos de la tabla
String titulos[] = {"ID Usuario","Cédula", "Nombres", "Apellidos", "Perfil", "F.
Ingreso"};
//registramos el número de columnas
String registro[] = new String[6];
//pasamos los titulos a la tabla
miTabla = new DefaultTableModel(null, titulos);
for (int i = 0; i < misUsuarios.size(); i++) {
registro[0] = misUsuarios.get(i).getIdUsuario();
registro[1] = ""+misUsuarios.get(i).getCi();
registro[2] = misUsuarios.get(i).getNombres();
registro[3] = misUsuarios.get(i).getApellidos();
registro[4] = perfil(misUsuarios.get(i).getPerfil());
registro[5] = formatDate(misUsuarios.get(i).getFechaIngreso());
miTabla.addRow(registro);
}
tblTabla.setModel(miTabla);
}
private String perfil(int idPerfil) {
switch (idPerfil) {
case 1:
return "Administrador";
case 2:
return "Cajero";
case 3:
return "Mesero";
}
return "perfil no definido";
}
//devuelve la posicion en el arreglo de usuarios
public int posicionUsuario(String usuario){
for(int i=0;i<misUsuarios.size(); i++){
if (misUsuarios.get(i).getIdUsuario().equals(usuario)){
return i;
}
}
return -1;
}
//devuelve un usuario modificado
public String modificarUsuario(Usuario miUsuario, int posicion){
misUsuarios.get(posicion).setNombres(miUsuario.getNombres());
misUsuarios.get(posicion).setApellidos(miUsuario.getApellidos());
misUsuarios.get(posicion).setPerfil(miUsuario.getPerfil());
misUsuarios.get(posicion).setCi(miUsuario.getCi());
misUsuarios.get(posicion).setClave(miUsuario.getClave());
misUsuarios.get(posicion).setFechaNac(miUsuario.getFechaNac());
misUsuarios.get(posicion).setFechaIngreso(miUsuario.getFechaIngreso());
return "Usuario modificado correctamente";
}
//para validar que la cedula sea un long
public boolean esLong(String cadena){
try{
Long.parseLong(cadena);
return true;
}catch(NumberFormatException ex){
return false;
}
}

//Método para convertir String en fecha


public Date StringDate(String fecha){
SimpleDateFormat formaDelTexto = new SimpleDateFormat("dd/MM/yyyy");
Date aux=null;
try{
aux=formaDelTexto.parse(fecha);
}catch(Exception ex){
}
return aux;
}
//Método para cambiar el formato de fecha a string
public String formatDate (Date fecha){
SimpleDateFormat formatodeltexto=new SimpleDateFormat("dd/MM/yyyy");
return formatodeltexto.format(fecha);
}
// Variables declaration - do not modify
private javax.swing.JButton btnAnterior;
private javax.swing.JButton btnBorrar;
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnGuardar;
private javax.swing.JButton btnModificar;
private javax.swing.JButton btnNuevo;
private javax.swing.JButton btnPrimero;
private javax.swing.JButton btnSiguiente;
private javax.swing.JButton btnUltimo;
private javax.swing.JComboBox<String> cmbPerfil;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblTabla;
private javax.swing.JTextField txtApellidos;
private javax.swing.JTextField txtCedula;
private javax.swing.JPasswordField txtClave;
private javax.swing.JPasswordField txtConfirmacion;
private com.toedter.calendar.JDateChooser txtFechaIngreso;
private com.toedter.calendar.JDateChooser txtFechaNac;
private javax.swing.JTextField txtIDUsuario;
private javax.swing.JTextField txtNombres;
// End of variables declaration
}

frmCambio
Design

Source
package Formularios;
import Clases.Usuario;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class frmCambio extends javax.swing.JDialog {
private String clave,id;
private static ArrayList<Usuario> misUsuarios = new ArrayList<>();
public void setUsuarios(ArrayList<Usuario> misUsuarios) {
this.misUsuarios = misUsuarios;
}
public void setClave(String clave){
this.clave=clave;
}
public void setID(String id){
this.id=id;
}
public frmCambio(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
@SuppressWarnings("unchecked")
Generated Code
private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {
String actual,nuevo,confirmacion;
actual=new String(txtActual.getPassword());
nuevo=new String(txtNuevo.getPassword());
confirmacion=new String(txtConfirmacion.getPassword());

//Validaciones de campos vacios


if(actual.equals("")){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar la clave "
+ "actual");
txtActual.setText(null);
txtNuevo.setText(null);
txtConfirmacion.setText(null);
txtActual.requestFocusInWindow();
return;
}
if(nuevo.equals("")){
JOptionPane.showMessageDialog(rootPane, "Ingrese una nueva clave");
txtNuevo.requestFocusInWindow();
return;
}
if(confirmacion.equals("")){
JOptionPane.showMessageDialog(rootPane, "Debe confirmar "
+ "su nueva clave");
txtConfirmacion.requestFocusInWindow();
return;
}
int pos=posicionUsuario(id);
if(misUsuarios.get(pos).cambioClave(actual, nuevo, confirmacion)==-1){
JOptionPane.showMessageDialog(rootPane, "La clave original no "
+ "corresponde al usuario actual");
txtActual.setText(null);
txtActual.requestFocusInWindow();
txtNuevo.setText(null);
txtConfirmacion.setText(null);
return;
}else{
if(misUsuarios.get(pos).cambioClave(actual, nuevo, confirmacion)==1){
JOptionPane.showMessageDialog(rootPane, "La clave y la "
+ "confirmación no coinciden");
txtNuevo.setText(null);
txtConfirmacion.setText(null);
return;
}else{
JOptionPane.showMessageDialog(rootPane, "Clave modificada con éxito");
this.setVisible(false);
}
}

public int posicionUsuario(String usuario){


for(int i=0;i<misUsuarios.size(); i++){
if (misUsuarios.get(i).getIdUsuario().equals(usuario)){
return i;
}
}
return -1;
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
public static void main(String args[]) {
Look and feel setting code (optional)
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
frmCambio dialog = new frmCambio(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAceptar;
private javax.swing.JButton btnCancelar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPasswordField txtActual;
private javax.swing.JPasswordField txtConfirmacion;
private javax.swing.JPasswordField txtNuevo;
// End of variables declaration
}

frmProductos
Design
Source
package Formularios;

import Clases.Producto;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class frmProductos extends javax.swing.JInternalFrame {
private int proAct ;
boolean nuevo;
private DefaultTableModel miTabla;
ArrayList<Producto> misProductos=new ArrayList<>();
public void setProductos(ArrayList<Producto> misProductos) {
this.misProductos = misProductos;
}
public frmProductos() {
initComponents();
proAct=0;
nuevo=false;
}
@SuppressWarnings("unchecked")
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {
//Validación de campos vacios
if (txtIDProducto.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe digitar un Id");
txtIDProducto.requestFocusInWindow();
return;
}
if (txtDescripcion.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe la descripción del
producto");
txtDescripcion.requestFocusInWindow();
return;
}

if (cmbCategoria.getSelectedIndex() == 0) {
JOptionPane.showMessageDialog(rootPane, "Debe seleccionar una categoría");
cmbCategoria.requestFocusInWindow();
return;
}
//validación de precio......
if(txtPrecio.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un precio");
txtPrecio.requestFocusInWindow();
return;
}
if(misProductos.get(0).validarPrecio(txtPrecio.getText())==1){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un valor
númerico");
txtPrecio.setText(null);
txtPrecio.requestFocusInWindow();
return;
}else{
if(misProductos.get(0).validarPrecio(txtPrecio.getText())==-1){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un valor mayor
que cero");
txtPrecio.setText(null);
txtPrecio.requestFocusInWindow();
return;
}
}
//validación de stock........
if (txtStock.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar la cantidad en
stock");
txtStock.requestFocusInWindow();
return;
}

if(!misProductos.get(0).validarcantidad(txtStock.getText())){
JOptionPane.showMessageDialog(rootPane, "Digite una cantidad mayor que
cero");
txtStock.setText(null);
txtStock.requestFocusInWindow();
return;
}
//Validación que el producto no exista
int pos = posicionProducto(txtIDProducto.getText());
if (nuevo) {
if (pos != -1) {
JOptionPane.showMessageDialog(rootPane, "Producto ya existe");
txtIDProducto.requestFocusInWindow();
return;
}
} else if (pos == -1) {
JOptionPane.showMessageDialog(rootPane, "Producto no existe");
txtIDProducto.requestFocusInWindow();
return;
}
//Creamnos el objeto product y los agregamos a datos
Producto miProducto = new Producto(txtIDProducto.getText(),
txtDescripcion.getText(),
Float.parseFloat(txtPrecio.getText()),
txtNota.getText(),
cmbCategoria.getSelectedIndex(),
Integer.parseInt(txtStock.getText()));
String mns;
if (nuevo) {
misProductos.add(miProducto);
JOptionPane.showMessageDialog(rootPane, "Producto agregado
correctamente");
} else {
mns =modificarProducto(miProducto, pos);
JOptionPane.showMessageDialog(rootPane, mns);
}
//habilitar botones
btnPrimero.setEnabled(true);
btnAnterior.setEnabled(true);
btnSiguiente.setEnabled(true);
btnUltimo.setEnabled(true);
btnNuevo.setEnabled(true);
btnModificar.setEnabled(true);
btnBorrar.setEnabled(true);
btnBuscar.setEnabled(true);
btnGuardar.setEnabled(false);
btnCancelar.setEnabled(false);
//Deshabilita los campos
txtIDProducto.setEnabled(false);
txtDescripcion.setEnabled(false);
txtPrecio.setEnabled(false);
txtNota.setEnabled(false);
cmbCategoria.setEnabled(false);
txtStock.setEnabled(false);
//Se actualiza los datos de la tabla
llenarTabla();
}
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {
String producto = JOptionPane.showInputDialog("Ingrese código del producto");
if (producto.equals("")) {
return;
}
int pos = posicionProducto(producto);
if (pos == -1) {
JOptionPane.showMessageDialog(rootPane, "El producto no existe");
return;
}
proAct = pos;
mostrarRegistro();
}
private void cmbCategoriaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
//Habilita los botones
btnPrimero.setEnabled(true);
btnAnterior.setEnabled(true);
btnSiguiente.setEnabled(true);
btnUltimo.setEnabled(true);
btnNuevo.setEnabled(true);
btnModificar.setEnabled(true);
btnBorrar.setEnabled(true);
btnBuscar.setEnabled(true);
btnGuardar.setEnabled(false);
btnCancelar.setEnabled(false);
//Deshabilita los campos
txtIDProducto.setEnabled(false);
txtDescripcion.setEnabled(false);
txtPrecio.setEnabled(false);
txtNota.setEnabled(false);
cmbCategoria.setEnabled(false);
txtStock.setEnabled(false);
}
private void btnPrimeroActionPerformed(java.awt.event.ActionEvent evt) {
proAct = 0;
mostrarRegistro();
}
private void btnUltimoActionPerformed(java.awt.event.ActionEvent evt) {
proAct = misProductos.size()- 1;
mostrarRegistro();
}
private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {
proAct--;
if (proAct == -1) {
proAct = misProductos.size()- 1;
}
mostrarRegistro();
}
private void btnSiguienteActionPerformed(java.awt.event.ActionEvent evt) {
proAct++;
if (proAct == misProductos.size()) {
proAct = 0;
}
mostrarRegistro();
}
private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {
//Habilitar deshabilitar los botones
btnPrimero.setEnabled(false);
btnAnterior.setEnabled(false);
btnSiguiente.setEnabled(false);
btnUltimo.setEnabled(false);
btnNuevo.setEnabled(false);
btnModificar.setEnabled(false);
btnBorrar.setEnabled(false);
btnBuscar.setEnabled(false);
btnGuardar.setEnabled(true);
btnCancelar.setEnabled(true);
//Habilita los campos
txtIDProducto.setEnabled(true);
txtDescripcion.setEnabled(true);
txtStock.setEnabled(true);
txtNota.setEnabled(true);
txtPrecio.setEnabled(true);
cmbCategoria.setEnabled(true);
cmbCategoria.setSelectedIndex(0);
//Limpiar Campos
txtIDProducto.setText(null);
txtDescripcion.setText(null);
txtStock.setText(null);
txtNota.setText(null);
txtPrecio.setText(null);
//Activar el flag de registro nuevo
nuevo = true;
//Damos Foco al campo ID
txtIDProducto.requestFocusInWindow();
}
private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {
int rpta = JOptionPane.showConfirmDialog(rootPane, "¿Está seguro que desea
borrar el registro?");
if (rpta != 0) {
return;
}
misProductos.remove(proAct);
JOptionPane.showMessageDialog(rootPane, "Producto borrado correctamente");
proAct = 0;
mostrarRegistro();
//actualizamos tabla
llenarTabla();
}
private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {
//Habilitar deshabilitar los botones
btnPrimero.setEnabled(false);
btnAnterior.setEnabled(false);
btnSiguiente.setEnabled(false);
btnUltimo.setEnabled(false);
btnNuevo.setEnabled(false);
btnModificar.setEnabled(false);
btnBorrar.setEnabled(false);
btnBuscar.setEnabled(false);
btnGuardar.setEnabled(true);
btnCancelar.setEnabled(true);
//Habilita los campos
txtIDProducto.setEnabled(false);
txtDescripcion.setEnabled(true);
txtStock.setEnabled(true);
txtNota.setEnabled(true);
txtPrecio.setEnabled(true);
cmbCategoria.setEnabled(true);
//Desactivar el flag de registro nuevo
nuevo = false;

//Damos Foco al campo ID


txtDescripcion.requestFocusInWindow();
}
private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
mostrarRegistro();
llenarTabla();
}
private void mostrarRegistro() {
txtIDProducto.setText(misProductos.get(proAct).getIdProducto());
txtDescripcion.setText(misProductos.get(proAct).getDescripcion());
txtPrecio.setText(String.valueOf(misProductos.get(proAct).getPrecio()));
txtNota.setText(misProductos.get(proAct).getNota());
txtStock.setText(String.valueOf(misProductos.get(proAct).getStock()));
cmbCategoria.setSelectedIndex(misProductos.get(proAct).getCategoria());
}
private void llenarTabla(){
//titulos de la tabla
String titulos[]={"ID
Producto","Descripción","Precio","Categoría","Stock","Nota"};
//registramos el número de columnas
String registro[]=new String[6];
//pasamos los titulos a la tabla
miTabla=new DefaultTableModel(null,titulos);
for(int i=0;i<misProductos.size();i++)
{
registro[0]=misProductos.get(i).getIdProducto();
registro[1]=misProductos.get(i).getDescripcion();
registro[2]=""+misProductos.get(i).getPrecio();
registro[3]=perfil(misProductos.get(i).getCategoria());
registro[4]=""+misProductos.get(i).getStock();
registro[5]=misProductos.get(i).getNota();

miTabla.addRow(registro);
}
tblTabla.setModel(miTabla);
}
private String perfil(int idPerfil){
switch (idPerfil) {
case 1:
return "Entrada";
case 2:
return "Sopa";
case 3:
return "Bebida";
case 4:
return "Ensalada";
case 5:
return "Licor";
}
return "Categoría no definida";
}
public int posicionProducto(String producto){
for(int i=0;i<misProductos.size(); i++){
if (misProductos.get(i).getIdProducto().equals(producto)){
return i;
}
}
return -1;
}
public String modificarProducto(Producto miProducto, int pos) {
misProductos.get(pos).setDescripcion(miProducto.getDescripcion());
misProductos.get(pos).setPrecio(miProducto.getPrecio());
misProductos.get(pos).setNota(miProducto.getNota());
misProductos.get(pos).setCategoria(miProducto.getCategoria());
return "Producto modificado corecctamente";
}
// Variables declaration - do not modify
private javax.swing.JButton btnAnterior;
private javax.swing.JButton btnBorrar;
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnGuardar;
private javax.swing.JButton btnModificar;
private javax.swing.JButton btnNuevo;
private javax.swing.JButton btnPrimero;
private javax.swing.JButton btnSiguiente;
private javax.swing.JButton btnUltimo;
private javax.swing.JComboBox<String> cmbCategoria;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tblTabla;
private javax.swing.JTextField txtDescripcion;
private javax.swing.JTextField txtIDProducto;
private javax.swing.JTextArea txtNota;
private javax.swing.JTextField txtPrecio;
private javax.swing.JTextField txtStock;
// End of variables declaration
}
frmPedido
Design

Source
package Formularios;

import Clases.Cliente;
import Clases.Mesero;
import Clases.Producto;
import Clases.Usuario;
import com.sun.corba.se.impl.orbutil.closure.Constant;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import sun.swing.table.DefaultTableCellHeaderRenderer;
/**
*
* @author EDGAR MENESES
*/
public class frmPedido extends javax.swing.JInternalFrame {

private DefaultTableModel miTablaMenu, miTablaPedido, aux;


private ArrayList<Usuario> misUsuarios = new ArrayList<>();
private ArrayList<Cliente> misClientes = new ArrayList<>();
private ArrayList<Producto> misProductos = new ArrayList<>();
private int mesa, fila;
private double sub, iva, total;

public void setMesa(int mesa) {


this.mesa = mesa;
}

public void setProductos(ArrayList<Producto> misProductos) {


this.misProductos = misProductos;
}

public void setUsuarios(ArrayList<Usuario> misUsuarios) {


this.misUsuarios = misUsuarios;
}

public void setClientes(ArrayList<Cliente> misClientes) {


this.misClientes = misClientes;
}
public frmPedido() {
sub = total = fila = 0;
iva = 0;
initComponents();
}

@SuppressWarnings("unchecked")
private void cmbMenuMouseClicked(java.awt.event.MouseEvent evt) {
}

private void cmbMenuMouseExited(java.awt.event.MouseEvent evt) {


}

private void cmbMenuActionPerformed(java.awt.event.ActionEvent evt) {


}

private void btnMuestreActionPerformed(java.awt.event.ActionEvent evt) {


ArrayList<Producto> aux = new ArrayList<>();
for (int i = 0; i < misProductos.size(); i++) {
if (misProductos.get(i).getCategoria() == cmbMenu.getSelectedIndex()) {
Producto ab = new Producto(
misProductos.get(i).getIdProducto(),
misProductos.get(i).getDescripcion(),
misProductos.get(i).getPrecio(),
misProductos.get(i).getNota(),
misProductos.get(i).getCategoria(),
misProductos.get(i).getStock());
aux.add(ab);
}
}
llenarTablaProdutos(aux);
}
private void txtTotalActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
jlabelMesa.setText("MESA " + mesa);
txtFecha.setText(formatDate(new Date()));
llenarTablaProdutos(misProductos);
cmbMesero.addItem("Seleccione un mesero");
for (int i = 0; i < misUsuarios.size(); i++) {
if (misUsuarios.get(i).getPerfil() == 3) {
cmbMesero.addItem(misUsuarios.get(i).getNombres());
}
}
llenarTablaPedido();
}
private void txtFechaActionPerformed(java.awt.event.ActionEvent evt) {
}
private void btnLicoresActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<Producto> aux = new ArrayList<>();
for (int i = 0; i < misProductos.size(); i++) {
if (misProductos.get(i).getCategoria() == 5) {
Producto ab = new Producto(
misProductos.get(i).getIdProducto(),
misProductos.get(i).getDescripcion(),
misProductos.get(i).getPrecio(),
misProductos.get(i).getNota(),
misProductos.get(i).getCategoria(),
misProductos.get(i).getStock());
aux.add(ab);
}
}
llenarTablaProdutos(aux);
}
private void btnSopasActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<Producto> aux = new ArrayList<>();
for (int i = 0; i < misProductos.size(); i++) {
if (misProductos.get(i).getCategoria() == 2) {
Producto ab = new Producto(
misProductos.get(i).getIdProducto(),
misProductos.get(i).getDescripcion(),
misProductos.get(i).getPrecio(),
misProductos.get(i).getNota(),
misProductos.get(i).getCategoria(),
misProductos.get(i).getStock());
aux.add(ab);
}
}
llenarTablaProdutos(aux);
}
private void btnEnsaladasActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<Producto> aux = new ArrayList<>();
for (int i = 0; i < misProductos.size(); i++) {
if (misProductos.get(i).getCategoria() == 4) {
Producto ab = new Producto(
misProductos.get(i).getIdProducto(),
misProductos.get(i).getDescripcion(),
misProductos.get(i).getPrecio(),
misProductos.get(i).getNota(),
misProductos.get(i).getCategoria(),
misProductos.get(i).getStock());
aux.add(ab);
}
}
llenarTablaProdutos(aux);
}
private void btnBebidasActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<Producto> aux = new ArrayList<>();
for (int i = 0; i < misProductos.size(); i++) {
if (misProductos.get(i).getCategoria() == 3) {
Producto ab = new Producto(
misProductos.get(i).getIdProducto(),
misProductos.get(i).getDescripcion(),
misProductos.get(i).getPrecio(),
misProductos.get(i).getNota(),
misProductos.get(i).getCategoria(),
misProductos.get(i).getStock());
aux.add(ab);
}
}
llenarTablaProdutos(aux);
}
private void btnEntradaActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<Producto> aux = new ArrayList<>();

for (int i = 0; i < misProductos.size(); i++) {


if (misProductos.get(i).getCategoria() == 1) {
Producto ab = new Producto(
misProductos.get(i).getIdProducto(),
misProductos.get(i).getDescripcion(),
misProductos.get(i).getPrecio(),
misProductos.get(i).getNota(),
misProductos.get(i).getCategoria(),
misProductos.get(i).getStock());
aux.add(ab);
}
}
llenarTablaProdutos(aux);
}
private void btnAumentarActionPerformed(java.awt.event.ActionEvent evt) {
int seleccion = tblMenu.getSelectedRow();
if (cmbMesero.getSelectedIndex() == 0) {
JOptionPane.showMessageDialog(rootPane, "Debe seleccionar un Mesero");
cmbMesero.requestFocusInWindow();
return;
}
if (seleccion == -1) {
JOptionPane.showMessageDialog(rootPane, "Debe seleccionar un plato");
tblMenu.requestFocusInWindow();
return;
}
if (txtCantidad.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe digitar una cantidad");
txtCantidad.setText(null);
txtCantidad.requestFocusInWindow();
return;
}
if (!esNumero(txtCantidad.getText())) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un dato numérico
en cantidad");
txtCantidad.setText(null);
txtCantidad.requestFocusInWindow();
return;
}
int cantidad = Integer.parseInt(txtCantidad.getText());
if (cantidad <= 0) {
JOptionPane.showMessageDialog(rootPane, "Digite una cantidad mayor que
cero");
txtCantidad.setText("1");
txtCantidad.requestFocusInWindow();
return;
}
//Buscamos el producto
int sel = tblMenu.getSelectedRow();
String idSeleccion = tblMenu.getValueAt(sel, 0).toString();
int pos = posicionProducto(idSeleccion);
int StockAct = misProductos.get(pos).getStock();
//Verificar el Stock
if (StockAct <= 0) {
JOptionPane.showMessageDialog(rootPane, "Producto agotado: "
+ misProductos.get(pos).getDescripcion());
return;
}
if (StockAct >= cantidad) {
misProductos.get(pos).setStock(StockAct - cantidad);
} else {
JOptionPane.showMessageDialog(rootPane, "No hay suficiente "
+ misProductos.get(pos).getDescripcion());
txtCantidad.setText("1");
return;
}
String registro[] = new String[4];
registro[0] = "" + (cantidad);
registro[1] = misProductos.get(pos).getDescripcion();
registro[2] = "" + misProductos.get(pos).getPrecio();
registro[3] = "" + (cantidad * misProductos.get(pos).getPrecio());
//añadimos prodcuto a la tabla
miTablaPedido.addRow(registro);
//Inicializamos campos
cmbMenu.setSelectedIndex(0);
txtCantidad.setText("1");
llenarTablaProdutos(misProductos);
cmbMesero.setEnabled(false);
//Actualizamos totales
actualizarTotales();
}
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
}
private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {
int seleccion = tblPedido.getSelectedRow();
int numFilas = tblPedido.getRowCount();
if (numFilas > 0) {
if (seleccion >= 0) {
DefaultTableModel mod = (DefaultTableModel) tblPedido.getModel();
mod.removeRow(seleccion);
actualizarTotales();
} else {
JOptionPane.showMessageDialog(rootPane, "No se ha seleccionado ningun
elemento");
}
} else {
JOptionPane.showMessageDialog(rootPane, "No hay elementos para borrar");
}
}
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {
int numFilas = tblPedido.getRowCount();
if (numFilas > 0) {
int rpta = JOptionPane.showConfirmDialog(rootPane, "¿Está seguro de que
Borrar el pedido");
if (rpta != 0) {
return;
}
llenarTablaPedido();
actualizarTotales();
cmbMesero.setSelectedIndex(0);
cmbMesero.setEnabled(true);
} else {
JOptionPane.showMessageDialog(rootPane, "No hay elementos para borrar");
}
}
private void btnLiberarMesaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnPagarActionPerformed(java.awt.event.ActionEvent evt) {
Mesero mozo=null;
for (int i = 0; i < misUsuarios.size(); i++) {
if
(cmbMesero.getItemAt(cmbMesero.getSelectedIndex()).equals(misUsuarios.get(i).getN
ombres())) {
mozo=new Mesero(misUsuarios.get(i).getCi(),
misUsuarios.get(i).getNombres(),
misUsuarios.get(i).getApellidos(),
misUsuarios.get(i).getIdUsuario(),
misUsuarios.get(i).getClave(),
misUsuarios.get(i).getPerfil(),
misUsuarios.get(i).getFechaNac(),
misUsuarios.get(i).getFechaIngreso());
}
}
if (tblPedido.getRowCount() != 0) {
frmFactura fact = new frmFactura(null, closable);
fact.setDetalle(miTablaPedido);
fact.setMesero(mozo);
fact.setClientes(misClientes);
fact.setProductos(misProductos);
fact.setLocationRelativeTo(null);
fact.setVisible(true);
} else {
JOptionPane.showMessageDialog(rootPane, "No se puede generar una factura,
si no hay pedidos");
}
}
//Método para cambiar el formato de fecha a string
public String formatDate(Date fecha) {
SimpleDateFormat formatodeltexto = new SimpleDateFormat("dd/MM/yyyy");
return formatodeltexto.format(fecha);

}
private void llenarTablaPedido() {
//titulos de la tabla
String titulos[] = {"Cantidad", "Descripción", "Valor unitario", "Importe"};
String registro[] = new String[4];
miTablaPedido = new DefaultTableModel(null, titulos);
tblPedido.setModel(miTablaPedido);
//alinear campos a la derecha
DefaultTableCellRenderer aux = new DefaultTableCellHeaderRenderer();
aux.setHorizontalAlignment(SwingConstants.RIGHT);
tblPedido.getColumnModel().getColumn(2).setCellRenderer(aux);
tblPedido.getColumnModel().getColumn(3).setCellRenderer(aux);
}
private void llenarTablaProdutos(ArrayList<Producto> misProductos) {
//titulos de la tabla
String titulos[] = {"ID Producto", "Descripción", "Categoría", "Precio", "Stock"};
//registramos el número de columnas
String registro[] = new String[5];
//pasamos los titulos a la tabla
miTablaMenu = new DefaultTableModel(null, titulos);
for (int i = 0; i < misProductos.size(); i++) {
registro[0] = misProductos.get(i).getIdProducto();
registro[1] = misProductos.get(i).getDescripcion();
registro[2] = perfil(misProductos.get(i).getCategoria());
registro[3] = "" + misProductos.get(i).getPrecio();
registro[4] = "" + misProductos.get(i).getStock();
miTablaMenu.addRow(registro);
}
tblMenu.setModel(miTablaMenu);

//alinear campos a la derecha


DefaultTableCellRenderer aux = new DefaultTableCellHeaderRenderer();
aux.setHorizontalAlignment(SwingConstants.RIGHT);
tblMenu.getColumnModel().getColumn(3).setCellRenderer(aux);
tblMenu.getColumnModel().getColumn(4).setCellRenderer(aux);
}
private String perfil(int idPerfil) {
switch (idPerfil) {
case 1:
return "Entrada";
case 2:
return "Sopa";
case 3:
return "Bebida";
case 4:
return "Ensalada";
case 5:
return "Licor";
}
return "Categoría no definida";
}
public int posicionProducto(String producto) {
for (int i = 0; i < misProductos.size(); i++) {
if (misProductos.get(i).getIdProducto().equals(producto)) {
return i;
} }
return -1;
}
private void actualizarTotales() {
int a = tblPedido.getRowCount();
sub = 0;
for (int i = 0; i < a; i++) {
sub += Float.parseFloat(miTablaPedido.getValueAt(i, 3).toString());
}
sub = (double) Math.round(sub * 100) / 100;
iva = ((sub * 14) / 100);
iva = (double) Math.round(iva * 100) / 100;
total = sub + iva;
total = (double) Math.round(total * 100) / 100;
txtSubTotal.setText(String.valueOf(sub));
txtIva.setText(String.valueOf(iva));
txtTotal.setText(String.valueOf(total));
}
private boolean esFloat(String cadena) {
try {
Float.parseFloat(cadena);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
private boolean esNumero(String cadena) {
try {
Integer.parseInt(cadena);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
// Variables declaration - do not modify
private javax.swing.JButton btnAumentar;
private javax.swing.JButton btnBack;
private javax.swing.JButton btnBebidas;
private javax.swing.JButton btnBorrar;
private javax.swing.JButton btnEliminar;
private javax.swing.JButton btnEnsaladas;
private javax.swing.JButton btnEntrada;
private javax.swing.JButton btnLiberarMesa;
private javax.swing.JButton btnLicores;
private javax.swing.JButton btnMuestre;
private javax.swing.JButton btnPagar;
private javax.swing.JButton btnSopas;
private javax.swing.JComboBox<String> cmbMenu;
private javax.swing.JComboBox<String> cmbMesero;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel jlabelMesa;
private javax.swing.JLabel jlabelMesa1;
private javax.swing.JTable tblMenu;
private javax.swing.JTable tblPedido;
private javax.swing.JTextField txtCantidad;
private javax.swing.JTextField txtFecha;
private javax.swing.JTextField txtIva;
private javax.swing.JTextField txtSubTotal;
private javax.swing.JTextField txtTotal;
// End of variables declaration
}
frmFactura
Design
Source

package Formularios;
import Clases.Cliente;
import Clases.Mesero;
import Clases.Producto;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import sun.swing.table.DefaultTableCellHeaderRenderer;
public class frmFactura extends javax.swing.JDialog {
private DefaultTableModel pedido, miDetalle;
private ArrayList<Cliente> misClientes;
private ArrayList<Producto> misProductos = new ArrayList<>();
private Cliente caserito;
private Mesero mozo;
public void setMesero(Mesero mesero) {
this.mozo = mesero;
}
public void setProductos(ArrayList<Producto> misProductos) {
this.misProductos = misProductos;
}
public void setClientes(ArrayList<Cliente> misClientes) {
this.misClientes = misClientes;
}
public void setDetalle(DefaultTableModel pedido) {
this.pedido = pedido;
}
public frmFactura(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
pedido = new DefaultTableModel();
caserito = new Cliente(0, null, null, null, null);
}
@SuppressWarnings("unchecked")
private void btnPagarFacturaActionPerformed(java.awt.event.ActionEvent evt) {
if (txtNombre.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el nombre del
cliente");
txtNombre.requestFocusInWindow();
} else if (txtCedula.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar el número de
cédula");
txtCedula.requestFocusInWindow();
} else if (txtTelefono.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un número
telefónico");
txtTelefono.requestFocusInWindow();
} else if (txtDireccion.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Debe ingresar una dirección");
txtDireccion.requestFocusInWindow();
} else if (!misClientes.get(0).validarCedula(Long.parseLong(txtCedula.getText())))
{
JOptionPane.showMessageDialog(rootPane, "El número de cédula no es
correcto");
txtCedula.setText("");
txtCedula.requestFocusInWindow();
} else {
ArrayList<Producto> prod = new ArrayList<>();
for (int j = 0; j < tblDetalle.getRowCount(); j++) {
boolean encontro=false;
int pos=0;
do {
if (tblDetalle.getValueAt(j,
1).equals(misProductos.get(pos).getDescripcion())) {
prod.add(misProductos.get(pos));
encontro=true;
}else{
pos++;
}
} while (encontro==false);
}
Pago miPago = new Pago(null, rootPaneCheckingEnabled);
miPago.setCliente(caserito);
miPago.setProductos(prod);
miPago.setMesero(mozo);
miPago.setTotal(txtTotal.getText());
miPago.setLocationRelativeTo(null);
miPago.setVisible(true);
}
}
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {
String ciCliente = JOptionPane.showInputDialog("Ingrese la cédula del cliente");

if (ciCliente.equals("")) {
return;
}
int pos = posicionCliente(ciCliente);
if (pos == -1) {
JOptionPane.showMessageDialog(rootPane, "El cliente no existe");
txtCedula.setText(null);
txtNombre.setText(null);
txtDireccion.setText(null);
txtTelefono.setText(null);
txtNombre.requestFocusInWindow();
return;
} else {
caserito = misClientes.get(pos);
txtCedula.setText("" + misClientes.get(pos).getCi());
txtNombre.setText(misClientes.get(pos).getNombres());
txtDireccion.setText(misClientes.get(pos).getDireccion());
txtTelefono.setText(misClientes.get(pos).getTelefono());
}
}
private void txtTelefonoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
llenarDetalle();
actualizarTotales();
int a;
a = (int) (Math.random() * 99 + 1);
txtNumFactura.setText("" + a);
txtfecha.setText(formatDate(new Date()));
txtNombre.requestFocusInWindow();
}
private void llenarDetalle() {
//titulos de la tabla
String titulos[] = {"Cantidad", "Descripción", "Valor unitario", "Importe"};
String registro[] = new String[4];
miDetalle = new DefaultTableModel(null, titulos);
for (int i = 0; i < pedido.getRowCount(); i++) {
registro[0] = "" + pedido.getValueAt(i, 0);
registro[1] = "" + pedido.getValueAt(i, 1);
registro[2] = "" + pedido.getValueAt(i, 2);
registro[3] = "" + pedido.getValueAt(i, 3);
miDetalle.addRow(registro);
}
tblDetalle.setModel(miDetalle);
//alinear campos a la derecha
DefaultTableCellRenderer aux = new DefaultTableCellHeaderRenderer();
aux.setHorizontalAlignment(SwingConstants.RIGHT);
tblDetalle.getColumnModel().getColumn(2).setCellRenderer(aux);
tblDetalle.getColumnModel().getColumn(3).setCellRenderer(aux);
}
private void actualizarTotales() {
int a = tblDetalle.getRowCount();
double sub, iva, total;
sub = 0;
for (int i = 0; i < a; i++) {
sub += Float.parseFloat(miDetalle.getValueAt(i, 3).toString());
}
sub = (double) Math.round(sub * 100) / 100;
iva = ((sub * 14) / 100);
iva = (double) Math.round(iva * 100) / 100;
total = sub + iva;
total = (double) Math.round(total * 100) / 100;
txtSubTotal.setText(String.valueOf(sub));
txtIva.setText(String.valueOf(iva));
txtTotal.setText(String.valueOf(total));
}
public int posicionCliente(String ciCliente) {
for (int i = 0; i < misClientes.size(); i++) {
if (misClientes.get(i).getCi() == (Long.parseLong(ciCliente))) {
return i;
}
}
return -1;
}
//Método para cambiar el formato de fecha a string
public String formatDate(Date fecha) {
SimpleDateFormat formatodeltexto = new SimpleDateFormat("dd/MM/yyyy");
return formatodeltexto.format(fecha);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
frmFactura dialog = new frmFactura(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnPagarFactura;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblDetalle;
private javax.swing.JTextField txtCedula;
private javax.swing.JTextField txtDireccion;
private javax.swing.JTextField txtIva;
private javax.swing.JTextField txtNombre;
private javax.swing.JTextField txtNumFactura;
private javax.swing.JTextField txtSubTotal;
private javax.swing.JTextField txtTelefono;
private javax.swing.JTextField txtTotal;
private javax.swing.JTextField txtfecha;
// End of variables declaration
}

frmPago
Design

Source

package Formularios;
import Clases.Cliente;
import Clases.Factura;
import Clases.Mesero;
import Clases.Producto;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
public class Pago extends javax.swing.JDialog {
private String Total;
private Cliente caserito;
private ArrayList<Producto> misProductos = new ArrayList<>();
private Mesero mozo;
public void setMesero(Mesero mesero) {
this.mozo = mesero;
}
public void setProductos(ArrayList<Producto> misProductos) {
this.misProductos = misProductos;
}
public void setTotal(String total){
this.Total=total;
}
public void setCliente(Cliente a){
this.caserito=a;
}
public Pago(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
@SuppressWarnings("unchecked")
private void txtIngresoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
txtTotal.setText(Total);
}
private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {
guardarFactura();
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
private void txtIngresoFocusLost(java.awt.event.FocusEvent evt) {
cambio();
}
private void txtIngresoKeyPressed(java.awt.event.KeyEvent evt) {
}
private void cambio(){
//Validaciones
if(txtIngreso.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un monto");
txtIngreso.setText(null);
txtCambio.setText(null);
txtIngreso.requestFocusInWindow();
return;
}
if(!esFloat(txtIngreso.getText())){
JOptionPane.showMessageDialog(rootPane, "Debe ingresar un valor
numerico");
txtIngreso.requestFocusInWindow();
return;}
float ingreso =Float.parseFloat(txtIngreso.getText());
float monto=Float.parseFloat(Total);
if(monto>ingreso){
JOptionPane.showMessageDialog(rootPane, "El monto no es suficiente");
txtIngreso.setText(null);
txtIngreso.requestFocusInWindow();
txtCambio.setText("");
return;
}
//Calculamos el vuelto
float cambio=ingreso-monto;
cambio= (float) Math.round(cambio * 100) / 100;
txtCambio.setText(String.valueOf(cambio));
}
private boolean esFloat(String cadena) {
try {
Float.parseFloat(cadena);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
private void guardarFactura() {
FileWriter fw=null;
PrintWriter pw=null;
Factura xx=new Factura(2, caserito, new Date(), mozo, misProductos);
try {
fw=new FileWriter("DatosSistema/Facturas.txt");
pw=new PrintWriter(fw);
pw.println(xx.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fw!=null){
fw.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Pago dialog = new Pago(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAceptar;
private javax.swing.JButton btnCancelar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField txtCambio;
private javax.swing.JTextField txtIngreso;
private javax.swing.JTextField txtTotal;
// End of variables declaration
}

frmAcercaDe
Design

Source

package Formularios;
public class frmAcercaDe extends javax.swing.JInternalFrame {
public frmAcercaDe() {
initComponents();
}
@SuppressWarnings("unchecked")
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}

CONCLUSIONES:
- La interfaz gráfica de usuario permite que las aplicaciones que desarrollemos
puedan interactuar con las personas que la utilizan y puedan ser optimizadas las
funciones para las que se la desarrolló, satisfaciendo al consumidor y
permitiéndolo entender sin necesidad de conocer acerca de programación.

- En los sucesos cotidianos se presentan diversos problemas en diferentes ámbitos


que forman parte de nuestro desarrollo de vida, por ello es importante que si
tenemos a disposición el uso e implementación de la programación para suplir
soluciones lo hagamos, aplicando nuestros conocimientos para el bien óptimo de
la sociedad, java permite el desarrollo de diversas funciones en su API y debemos
entenderlas para que todo esto se pueda evitar o solventar dichas situaciones.

- El uso de archivos es importante en las aplicaciones que generamos para guardar


la infomación que desarrollamos, porque en las situaciones reales requerimos que
la información sea guardada y no solo mostrada en consola por un instante.

RECOMENDACIONES:
Es importante que analizemos los mejores procesos y más cortos que cumplan con las
especificaciones necesarias, por ello debemos desarrollar la lógica y el conocimiento de
los procesos que se desarrollan en Java.

You might also like