creacion de Controladores y cambios en Vista y Modelo

This commit is contained in:
Soka_jplr 2024-03-10 16:11:32 -06:00
parent eb45b06de4
commit e6210edd09
13 changed files with 231 additions and 88 deletions

View File

@ -1,6 +1,9 @@
create database cocina; create database cocina;
use cocina; use cocina;
#Crear un usuario para ocuparlo en el programa y no estar cambiando el archivo conexion.java
CREATE USER 'UserRemoto' @'localhost' IDENTIFIED BY 'password123';
GRANT ALL PRIVILEGES ON cocina TO 'UserRemoto' @'localhost';
FLUSH PRIVILEGES;
drop table usuarios; drop table usuarios;
create table usuarios( create table usuarios(

View File

@ -73,7 +73,7 @@ jlink.additionalmodules=
jlink.additionalparam= jlink.additionalparam=
jlink.launcher=true jlink.launcher=true
jlink.launcher.name=SalaDeConciertos jlink.launcher.name=SalaDeConciertos
main.class= main.class=Main.Main
manifest.file=manifest.mf manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false mkdist.disabled=false

View File

@ -1,13 +0,0 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Controlador;
/**
*
* @author juanl
*/
public class Controlador {
}

View File

@ -0,0 +1,54 @@
package Controlador;
import Modelo.Consulta;
import Modelo.Usuario;
import Vista.Login;
import Vista.Registro;
import Vista.SalaPrincipal;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/*
* @author Juan Ska
*/
public class ControladorLogin implements ActionListener{
private Login login;
private Consulta consulta = new Consulta();
public ControladorLogin(Login login) {
this.login = login;
}
@Override
public void actionPerformed(ActionEvent e) {
//Valora que boton presiono el Usuario.
if(e.getSource()== login.getBtnLogin()){
String valorPass = new String(login.getTxtContraseñaLogin().getPassword());
//Valora si los campos etan vacios
if(login.getTxtNombreUsuario().getText().isEmpty()||valorPass.isEmpty()){
JOptionPane.showMessageDialog(null, "Error. Favor de llenar Todos los campos");
}else{
//Busca al usuario en la base de datos
Usuario user = new Usuario(login.getTxtNombreUsuario().getText(), valorPass);
if(consulta.verificarUsuario(user)){
//Abre una nueva ventana
JOptionPane.showMessageDialog(null, "Bienvenido " + user.getNombre());
SalaPrincipal principal = new SalaPrincipal(user);
principal.setVisible(true);
login.dispose();
}else{
JOptionPane.showMessageDialog(null, "Error. Nombre de usuario o Contraseña incorrectas");
}
}
}
//Abre la ventana de registro
if(e.getSource()== login.getBtnRegistrarse()){
Registro registro = new Registro();
registro.setLocationRelativeTo(null);
registro.setVisible(true);
login.dispose();
}
}
}

View File

@ -0,0 +1,56 @@
package Controlador;
import Modelo.Consulta;
import Vista.Registro;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/*
* @author Juan Ska
*/
public class ControladorRegistro extends Thread{
private Registro registro;
private String name="";
private Consulta consulta = new Consulta();
public ControladorRegistro(Registro registro) {
this.registro = registro;
run();
}
@Override
public void run(){
registro.getBtnRegistrar().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
});
registro.getTxtNombreUsuarioRegistro().addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
name = registro.getTxtNombreUsuarioRegistro().getText();
if(consulta.usuarioInvalido(name)){
registro.getLabelName().setForeground(Color.red);
registro.getLabelName().setText("No puedes usar ese nombre");
registro.getBtnRegistrar().setEnabled(false);
}else{
registro.getLabelName().setForeground(Color.GREEN);
registro.getLabelName().setText("Nombre Disponible");
registro.getBtnRegistrar().setEnabled(true);
}
}
});
}
}

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,8 +1,13 @@
package Main; package Main;
import Vista.Login;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
Login login = new Login();
login.setLocationRelativeTo(null);
login.setVisible(true);
} }
} }

48
src/Modelo/Conexion.java Normal file
View File

@ -0,0 +1,48 @@
package Modelo;
import java.sql.*;
public class Conexion {
private static Connection conexion;
private static Conexion istancia;
private static final String url = "jdbc:mysql://localhost:3306/cocina";
private static final String user = "UserRemoto";
private static final String password ="password123";
private Conexion(){}
public Connection conectar(){
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conexion = DriverManager.getConnection(url, user, password);
if(conexion!=null){
System.out.println("Conexion Exitosa");
return conexion;
}else{
System.out.println("ERROR no se pudo conectar");
}
} catch (Exception e) {
System.out.println("ERROR: " + e);
}
return conexion;
}
public void cerrarconexion() throws SQLException{
try {
conexion.close();
System.out.println("Se desconecto de la base");
} catch (Exception e) {
System.out.println("ERROR: " + e);
conexion.close();
}finally{
conexion.close();
}
}
public static Conexion getInstance(){
if(istancia==null){
istancia = new Conexion();
}
return istancia;
}
}

55
src/Modelo/Consulta.java Normal file
View File

@ -0,0 +1,55 @@
package Modelo;
import java.sql.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Consulta {
private static final Conexion cn = Conexion.getInstance();
private static Connection conexion;
public Consulta(){}
public boolean verificarUsuario(Usuario user){
boolean verificacion =false;
try {
conexion = cn.conectar();
Statement stm;
String sql ="select * from Usuarios "
+ "where nombreUsuario= '"+user.getNombre()+"' and password='"+user.getPassword()+"'";
stm = conexion.createStatement();
ResultSet resultado = stm.executeQuery(sql);
if(resultado.next()){
verificacion = true;
}else{
verificacion = false;
}
cn.cerrarconexion();
} catch (SQLException ex) {
System.err.println(ex);
}
return verificacion;
}
public boolean usuarioInvalido(String name) {
boolean verificacion =false;
try {
conexion = cn.conectar();
Statement stm;
String sql ="select * from Usuarios "
+ "where nombreUsuario= '"+name+"'";
stm = conexion.createStatement();
ResultSet resultado = stm.executeQuery(sql);
if(resultado.next()){
verificacion = true;
}else{
verificacion = false;
}
cn.cerrarconexion();
} catch (SQLException ex) {
System.err.println(ex);
}
return verificacion;
}
}

View File

@ -1,13 +0,0 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Modelo;
/**
*
* @author juanl
*/
public class Modelo {
}

View File

@ -18,6 +18,12 @@ public class Usuario {
public Usuario(){ public Usuario(){
} }
public Usuario(String nombre, String password) {
this.nombre = nombre;
this.password = password;
}
public String getNombre() { public String getNombre() {
return nombre; return nombre;
} }

View File

@ -1,10 +0,0 @@
package Vista;
/**
*
* @author juanl
*/
public class Vista {
}

View File

@ -1,27 +1,14 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package Vista; package Vista;
/** /**
* *
* @author reyes * @author reyes
*/ */
public class seleccionarBoleto extends javax.swing.JFrame { public class SeleccionarBoleto extends javax.swing.JFrame {
/** public SeleccionarBoleto() {
* Creates new form seleccionarBoleto
*/
public seleccionarBoleto() {
initComponents(); initComponents();
} }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() { private void initComponents() {
@ -46,7 +33,6 @@ public class seleccionarBoleto extends javax.swing.JFrame {
jButton1 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMaximumSize(new java.awt.Dimension(32767, 32767));
jPanel1.setBackground(new java.awt.Color(249, 244, 244)); jPanel1.setBackground(new java.awt.Color(249, 244, 244));
@ -206,40 +192,6 @@ public class seleccionarBoleto extends javax.swing.JFrame {
pack(); pack();
}// </editor-fold>//GEN-END:initComponents }// </editor-fold>//GEN-END:initComponents
/**
* @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(seleccionarBoleto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(seleccionarBoleto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(seleccionarBoleto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(seleccionarBoleto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new seleccionarBoleto().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables // Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1; private javax.swing.JButton jButton1;