Você está na página 1de 27

Johan Leonardo Alarcon de La Flor 1

AP7-AA3-Ev1-Desarrollo del Tutorial Construcción de aplicación con


Java

Presentado Por:
Johan Leonardo Alarcon De La Flor

Tutor:
Julián Ernesto Trespalacios

Servicio Nacional de Aprendizaje (SENA)


Centro Biotecnológico del Caribe
Análisis y Desarrollo de Sistemas de Información
Colombia
2018
Johan Leonardo Alarcon de La Flor 2

Como parte de los materiales del curso, se presenta el tutorial de construcción de una
aplicación con Java, el cual es una guía paso a paso para implementar el caso de uso
“Administrar datos de pacientes” que se ha presentado como ejemplo dentro del desarrollo del
programa. El tutorial está dividido en 8 sesiones que aportan diferentes componentes a la
construcción de la aplicación distribuidas de la siguiente manera:

1. Sesión 1: Construyendo la base de datos

Tabla Citas:

Tabla Consultorios:
Johan Leonardo Alarcon de La Flor 3

Tabla Médicos:

Tabla Pacientes:
Johan Leonardo Alarcon de La Flor 4

Tabla Tratamientos:

2. Sesión 2: Desarrollando la Interfaz Gráfica de Usuario (GUI)


Johan Leonardo Alarcon de La Flor 5
Johan Leonardo Alarcon de La Flor 6

3. Sesión 3: Creando el Modelo de la Aplicación

Clase Paciente:
package modelo;

public class Paciente {


private String identificacion;
Johan Leonardo Alarcon de La Flor 7

private String nombres;


private String apellidos;
private String fechaNacimiento;
private String sexo;

public Paciente(String id, String nom, String ape, String fechaNac, String sex){
identificacion = id;
nombres = nom;
apellidos = ape;
fechaNacimiento = fechaNac;
sexo = sex;
}
public String getIdentificacion() {
return identificacion;
}
public void setIdentificacion(String identificacion) {
this.identificacion = identificacion;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
Johan Leonardo Alarcon de La Flor 8

this.apellidos = apellidos;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
}

Clase Gestor Paciente:

package modelo;

import java.util.LinkedList;

public class GestorPaciente {

private static LinkedList<Paciente> pacientes;

public GestorPaciente(){
Johan Leonardo Alarcon de La Flor 9

pacientes = new LinkedList<Paciente>();

}
public void registrarPaciente(Paciente paciente){
pacientes.add(paciente);
}

public LinkedList<Paciente> getPacientesBy(int parametro, String valor){

LinkedList<Paciente> resultado = new LinkedList<Paciente>();

for(Paciente pac: pacientes){

switch (parametro){

case 1: if(pac.getIdentificacion() .equals(valor))


resultado.add(pac);
break;
case 2: if(pac.getNombres() .equals(valor))
resultado.add(pac);
break;
case 3: if(pac.getApellidos().equals(valor))
resultado.add(pac);
break;
case 4: if(pac.getSexo().equals(valor))
resultado.add(pac);
break;
}
Johan Leonardo Alarcon de La Flor 10

}
return resultado;
}
}

4. Sesión 4: Enlazando con el Controlador

Modelo Vista Controlador (MVC):


Clase Paciente Control:

package controlador;
import java.awt.event.ActionEvent;
Johan Leonardo Alarcon de La Flor 11

import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;

public class PacienteControl implements ActionListener{

vista.RegPacienteInternalFrame pacienteVista;
modelo.Paciente pacienteModelo;
modelo.GestorPaciente gestorPacienteModelo;

public PacienteControl(vista.RegPacienteInternalFrame pacienteVista){


this.pacienteVista = pacienteVista;
gestorPacienteModelo = new modelo.GestorPaciente();
}

@Override
public void actionPerformed(ActionEvent e) {

if(e.getSource().equals(pacienteVista.RegistrarBtn)){

String identificacion = pacienteVista.IdentificacionTxt.getText();


String nombres = pacienteVista.NombresTxt.getText();
String apellidos = pacienteVista.ApellidosTxt.getText();
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yy");
String fechaNacimiento = formato.format(pacienteVista.FechaNacimientoDtc.getDate());
String sexo = null;
if(pacienteVista.MasculinoOpt.isSelected())
sexo = "m";
else
Johan Leonardo Alarcon de La Flor 12

sexo = "f";
pacienteModelo = new modelo.Paciente(identificacion, nombres, apellidos,
fechaNacimiento, sexo);
gestorPacienteModelo.registrarPaciente(pacienteModelo);
}
if(e.getSource().equals(pacienteVista.NuevoBtn)){

pacienteVista.IdentificacionTxt.setText(null);
pacienteVista.NombresTxt.setText(null);
pacienteVista.ApellidosTxt.setText(null);
pacienteVista.FechaNacimientoDtc.setDate(null);
pacienteVista.MasculinoOpt.setSelected(false);
pacienteVista.FemeninoOpt.setSelected(false);
pacienteVista.IdentificacionTxt.requestFocus();
}
}
}

Clase Gestor Paciente Control:


package controlador;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;

public class GestorPacienteControl implements ActionListener{

modelo.GestorPaciente pacientesModelo;
vista.ConsPacienteInternalFrame consultarPacienteVista;
Johan Leonardo Alarcon de La Flor 13

public GestorPacienteControl(vista.ConsPacienteInternalFrame consultarPacienteVista){


this.consultarPacienteVista = consultarPacienteVista;
pacientesModelo = new modelo.GestorPaciente();
}

@Override
public void actionPerformed(ActionEvent e) {

String valor = consultarPacienteVista.ValorTxt.getText();


int parametro = 0;
consultarPacienteVista.getTableModel().setRowCount(0);
consultarPacienteVista.getTableModel().fireTableDataChanged();
if(consultarPacienteVista.IdentificacionOpt.isSelected())
parametro = 1;
if(consultarPacienteVista.NombresOpt.isSelected())
parametro = 2;
if(consultarPacienteVista.ApellidosOpt.isSelected())
parametro = 3;
if(consultarPacienteVista.SexoOpt.isSelected())
parametro = 4;

LinkedList<modelo.Paciente> pacientes = pacientesModelo.getPacientesBy(parametro,


valor);
String registro[] = new String [5];
for(modelo.Paciente p:pacientes){

registro [0] = p.getIdentificacion();


registro [1] = p.getNombres();
Johan Leonardo Alarcon de La Flor 14

registro [2] = p.getApellidos();


registro [3] = p.getFechaNacimiento();
registro [4] = p.getSexo();
consultarPacienteVista.getTableModel().addRow(registro);
consultarPacienteVista.getTableModel().fireTableDataChanged();
}
}
}
Johan Leonardo Alarcon de La Flor 15

5. Sesión 5: Probando el Modelo Vista Controlador MVC

package vista;
public class PrincipalJFrame extends javax.swing.JFrame {
RegPacienteInternalFrame regPacienteInternalFrame;
ConsPacienteInternalFrame consPacienteInternalFrame;

public PrincipalJFrame() {
regPacienteInternalFrame = new RegPacienteInternalFrame();
consPacienteInternalFrame = new ConsPacienteInternalFrame();
add(regPacienteInternalFrame);
add(consPacienteInternalFrame);
initComponents();
setExtendedState(MAXIMIZED_BOTH);
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jMenuBar1 = new javax.swing.JMenuBar();


jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Johan Leonardo Alarcon de La Flor 16

setTitle("GESTION DE CITAS");
setName("PrincipalJFrame"); // NOI18N

jMenu1.setText("Archivo");
jMenu1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu1ActionPerformed(evt);
}
});

jMenuItem1.setText("Salir");
jMenu1.add(jMenuItem1);

jMenuBar1.add(jMenu1);

jMenu2.setText("Pacientes");
jMenu2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu2ActionPerformed(evt);
}
});

jMenuItem2.setText("Registrar");
jMenu2.add(jMenuItem2);

jMenuItem3.setText("Consultar");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Johan Leonardo Alarcon de La Flor 17

jMenuItem3ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem3);

jMenuBar1.add(jMenu2);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);

pack();
}// </editor-fold>
private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
regPacienteInternalFrame.setVisible(true);
}
Johan Leonardo Alarcon de La Flor 18

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


consPacienteInternalFrame.setVisible(true);
}

6. Sesión 6: Accediendo a la Base de Datos con JDBC


Johan Leonardo Alarcon de La Flor 19

package modelo;

import java.util.LinkedList;
import java.sql.*;
import javax.swing.JOptionPane;

public class GestorPaciente {

private static Connection conn;

public GestorPaciente(){
Johan Leonardo Alarcon de La Flor 20

recurso.Conexion conexion = new recurso.Conexion("localhost", "XE", "citas", "citas");


conn = conexion.getConexion();
}
public void registrarPaciente(Paciente paciente){

try{
PreparedStatement pst = conn.prepareStatement("insert into PACIENTES values (?, ?, ?,
?, ?)");
pst.setString(1, paciente.getIdentificacion());
pst.setString(2, paciente.getNombres());
pst.setString(3, paciente.getApellidos());
pst.setString(4, paciente.getFechaNacimiento());
pst.setString(5, paciente.getSexo());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Paciente Registrado!");
}
catch(SQLException exc){

JOptionPane.showMessageDialog(null, exc.getMessage());
}
}
public LinkedList<Paciente> getPacientesBy(int parametro, String valor){

LinkedList<Paciente> resultado = new LinkedList<Paciente>();


String sql = "";
switch (parametro){

case 1: sql = "select * from PACIENTES where pacIdentificacion = ' "+valor+" ' ";
Johan Leonardo Alarcon de La Flor 21

break;
case 2: sql = "select * from PACIENTES where pacNombres = ' "+valor+" ' ";
break;
case 3: sql = "select * from PACIENTES where pacApellidos = ' "+valor+" ' ";
break;
case 4: sql = "select * from PACIENTES where pacSexo = ' "+valor+" ' ";
break;
}
try{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);

while(rs.next()){

resultado.add(new Paciente(rs.getString("pacIdentificacion"),
rs.getString("pacNombres"),
rs.getString("pacApellidos"),
rs.getString("pacFechaNacimiento"),
rs.getString("pacSexo")));
}
st.close();
rs.close();
}
catch(SQLException exc){

JOptionPane.showMessageDialog(null, exc.getMessage());
}
finally{
Johan Leonardo Alarcon de La Flor 22

return resultado;
}
}
}

7. Sesión 7: Accediendo a la Base de Datos con JPA


Johan Leonardo Alarcon de La Flor 23

8. Sesión 8: Generando reportes impresos


Johan Leonardo Alarcon de La Flor 24
Johan Leonardo Alarcon de La Flor 25
Johan Leonardo Alarcon de La Flor 26

Clase Gestor Reportes:

package reportes;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;

public class GestorReportes {

private static Connection conexion;

public GestorReportes(){

String driver = "oracle.jdbc.driver.OracleDriver";


String url = "jdbc:oracle:thin:@localhost:1521:XE";

try{
Class.forName(driver).newInstance();
conexion = DriverManager.getConnection(url, "citas", "citas");
}
catch (Exception ex){
Johan Leonardo Alarcon de La Flor 27

JOptionPane.showMessageDialog(null, "Error de conexion con la base de datos");


}
}
public void ejecutarReporte(String archivo){

try{

String Reporte = System.getProperty("user.dir") + "/src/reportes/" + archivo;


JasperReport masterReport = (JasperReport)JRLoader.loadObject(Reporte);
JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, null, conexion);
JasperViewer jviewer = new JasperViewer(jasperPrint, false);
jviewer.setVisible(true);
}
catch (Exception ex){

JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());


}

Você também pode gostar