Professional Documents
Culture Documents
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.
package Clases;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Administrador extends Usuario{
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;
}
CLIENTE
package Clases;
public class Cliente extends Persona{
private String direccion;
private String telefono;
FACTURA
package Clases;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
MESA
package Clases;
public class Mesa {
private int numero;
private int 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;
PERSONA
package Clases;
public class Persona {
protected long ci;
protected String 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;
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 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;
//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);
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;
//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;
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;
//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);
}
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;
}
.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 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];
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);
}
/**
* @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);
}
});
}
try {
fw=new FileWriter("DatosSistema/Usuarios.txt");
pw=new PrintWriter(fw);
} 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);
} 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;
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;
}
usuAct = 0;
mostrarRegistro();
}
private void btnPrimeroActionPerformed(java.awt.event.ActionEvent evt) {
usuAct = 0;
mostrarRegistro();
}
//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;
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 {
//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);
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());
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;
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 {
@SuppressWarnings("unchecked")
private void cmbMenuMouseClicked(java.awt.event.MouseEvent evt) {
}
}
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);
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);
}
});
}
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.
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.