Sie sind auf Seite 1von 50

TUTORIAL CREAR APLICACION JAVA

SESION 1: CONSTRUYENDO LA BASE DE DATOS:

Tablas
Citas:

Consultorios:

Medicos:
Pacientes:

Tratamiento:

SESION 2: DESARROLLANDO LA VISTA INTERCE GRAFICA DE USUARIO(GUI):


SESION 3: CREANDO EL MODELO DE LA APLICACIÓN:
CLASE PACIENTE:
package modelo;

public class Paciente {


private String identificacion;
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;

Paciente(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To change
body of generated methods, choose Tools | Templates.
}
/**
*
* @return the identificacion
*/

public String getIdentificacion() {


return identificacion;
}
/**
*
* @param identificacion the identificacion to set
*/

public void setIdentificacion(String identificacion) {


this.identificacion = identificacion;
}
/**
*
* @return the nombres
*/

public String getNombres() {


return nombres;
}
/**
*
* @param nombre the nombres to set
*/

public void getNombres(String nombre) {


this.nombres = nombre;
}

/**
*
* @return the apellidos
*/
public String getApellidos() {
return apellidos;
}
/**
*
* @param apellidos the apellidos to set
*/

public void setApellidos(String apellidos) {


this.apellidos = apellidos;

}
/**
*
* @return the fechaNacimiento
*/

public String getFechaNacimiento() {


return fechaNacimiento;
}
/**
*
* @param fechaNacimiento the fechaNacimiento to set
*/

public void setFechaNacimiento(String fechaNacimiento) {


this.fechaNacimiento = fechaNacimiento;
}
/**
*
* @return the sexo
*/

public String getSexo() {


return sexo;
}
/**
*
* @param sexo the sexo to set
*/

public void setSexo(String sexo) {


this.sexo = sexo;
}

CLASE GESTOR PACIENTE:


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

public class GestorPaciente {


private static Connection conn;

public GestorPaciente()
{
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<>();
String sql="";
switch(parametro)
{
case 1: sql="select * from PACIENTES where pacIdentificacion="+valor+"";
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
{
ResultSet rs;
try (Statement st = conn.createStatement()) {
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")));

}
}
rs.close();
}
catch (SQLException exc)
{
JOptionPane.showMessageDialog(null,exc.getMessage());
}
finally
{

return resultado;

}
}

SESION: ENLAZANDO CON EL CONTROLADOR:


CLASE PACIENTE CONTROL:
package Controlador;

import java.awt.event.ActionEvent;
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();

public void actionPerformedd(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/yyyy");
String
fechaNacimiento=formato.format(pacienteVista.FechaNacimientoDtc.getDate());
String sexo=null;

if(pacienteVista.MasculinoOpt.isSelected())
sexo="m";
else
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();

@Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet."); //To change
body of generated methods, choose Tools | Templates.
}

}
CLASE CONTROLADOR GESTION 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;

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(parametr
o, valor);
String registro[] =new String [5];
for(modelo.Paciente p:pacientes)
{
registro[0]=p.getIdentificacion();
registro[1]=p.getNombres();
registro[2]=p.getApellidos();
registro[3]=p.getFechaNacimiento();
registro[4]=p.getSexo();
consultarPacienteVista.getTableModel().addRow(registro);
consultarPacienteVista.getTableModel().fireTableDataChanged();

SESION 5: PROBANDO EL MODELO VISTA CONTROLADOR(MVC)


FORMULARIO PRINCIPAL:
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();
jMenuItem4 = 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);
setTitle("GESTION DE CITAS");
setName("PrincipalJPrame"); // NOI18N

jMenu1.setText("Archivo");
jMenu1.setName("Imprimir Pacientes Registrados"); // NOI18N
jMenu1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu1ActionPerformed(evt);
}
});

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

jMenuItem4.setText("Imprimir Pacientes Registrados");


jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem4);

jMenuBar1.add(jMenu1);

jMenu2.setText("Pacientes");

jMenuItem2.setText("Registrar");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem2);
jMenuItem3.setText("Consultar");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
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 jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
regPacienteInternalFrame.setVisible(true);
}

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


consPacienteInternalFrame.setVisible(true);
}

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


reportes.GestorReportes gr=new reportes.GestorReportes();
gr.ejecutarReporte("PacientesReport.jasper");
}

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(PrincipalJFrame.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {

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

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

java.util.logging.Logger.getLogger(PrincipalJFrame.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new PrincipalJFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
// End of variables declaration

private static class RegPacienteInternalframe extends RegPacienteInternalFrame


{

public RegPacienteInternalframe() {
}
}
}

CONSPACIENTEINTERNALFRAME:
package vista;
import javax.swing.table.DefaultTableModel;

public class ConsPacienteInternalFrame extends javax.swing.JInternalFrame


{

private final controlador.GestorPacienteControl gestorpacientesControl;


private final DefaultTableModel tabla;

public ConsPacienteInternalFrame() {
initComponents();
gestorpacientesControl=new controlador.GestorPacienteControl(this);
String titulosTabla[]={"Identificacion","Nombres","Apellidos","Fecha
Nac","sexo"};
tabla = new DefaultTableModel(null, titulosTabla);
ResultadosTbl.setModel(tabla);
AceptarBtn.addActionListener(gestorpacientesControl);//
}
public DefaultTableModel getTableModel()
{
return tabla;

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

buttonGroup1 = new javax.swing.ButtonGroup();


IdentificacionOpt = new javax.swing.JRadioButton();
NombresOpt = new javax.swing.JRadioButton();
ApellidosOpt = new javax.swing.JRadioButton();
SexoOpt = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
ValorTxt = new javax.swing.JTextField();
AceptarBtn = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
ResultadosTbl = new javax.swing.JTable();

setTitle("Consulta de Pacientes");

buttonGroup1.add(IdentificacionOpt);
IdentificacionOpt.setText("Identificacion");
buttonGroup1.add(NombresOpt);
NombresOpt.setText("Nombres");

buttonGroup1.add(ApellidosOpt);
ApellidosOpt.setText("Apellidos");

buttonGroup1.add(SexoOpt);
SexoOpt.setText("Sexo");

jLabel1.setText("Valor a buscar");

ValorTxt.setName("ValorTxt"); // NOI18N

AceptarBtn.setText("Aceptar");
AceptarBtn.setName("AceptarBtn"); // NOI18N

ResultadosTbl.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
ResultadosTbl.setName("ResultadosTbl"); // NOI18N
jScrollPane1.setViewportView(ResultadosTbl);
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.LEADIN
G)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G)
.addComponent(IdentificacionOpt)
.addComponent(jLabel1))

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

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G)
.addGroup(layout.createSequentialGroup()
.addComponent(NombresOpt)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ApellidosOpt)
.addGap(18, 18, 18)
.addComponent(SexoOpt))
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(ValorTxt,
javax.swing.GroupLayout.PREFERRED_SIZE, 131,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AceptarBtn))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE, 359,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(36, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELI
NE)
.addComponent(IdentificacionOpt)
.addComponent(NombresOpt)
.addComponent(ApellidosOpt)
.addComponent(SexoOpt))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELI
NE)
.addComponent(jLabel1)
.addComponent(ValorTxt, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AceptarBtn))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE,
294, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

// Variables declaration - do not modify


public javax.swing.JButton AceptarBtn;
public javax.swing.JRadioButton ApellidosOpt;
public javax.swing.JRadioButton IdentificacionOpt;
public javax.swing.JRadioButton NombresOpt;
public javax.swing.JTable ResultadosTbl;
public javax.swing.JRadioButton SexoOpt;
public javax.swing.JTextField ValorTxt;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}

REGPACIENTEINTERNALFRAME:
package vista;

public class RegPacienteInternalFrame extends javax.swing.JInternalFrame


{

private controlador.PacienteControl pacienteControlador;


public RegPacienteInternalFrame()
{
initComponents();
pacienteControlador=new controlador.PacienteControl(this);
RegistrarBtn.addActionListener(pacienteControlador);
NuevoBtn.addActionListener(pacienteControlador);

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">


private void initComponents() {

jLabel1 = new javax.swing.JLabel();


jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
IdentificacionTxt = new javax.swing.JTextField();
NombresTxt = new javax.swing.JTextField();
ApellidosTxt = new javax.swing.JTextField();
MasculinoOpt = new javax.swing.JRadioButton();
FemeninoOpt = new javax.swing.JRadioButton();
RegistrarBtn = new javax.swing.JButton();
NuevoBtn = new javax.swing.JButton();
FechaNacimientoDtc = new com.toedter.calendar.JDateChooser();

setClosable(true);
setTitle("Registro de pacientes");

jLabel1.setText("Identificacion:");

jLabel2.setText("Nombres:");
jLabel3.setText("Apellidos:");

jLabel4.setText("Fecha de Nacimiento:");

jLabel5.setText("Sexo:");

IdentificacionTxt.setName("IdentificacionTxt"); // NOI18N

NombresTxt.setName("NombresTxt"); // NOI18N

ApellidosTxt.setName("ApellidosTxt"); // NOI18N

MasculinoOpt.setText("M");

FemeninoOpt.setText("F");

RegistrarBtn.setText("Registrar");
RegistrarBtn.setName("RegistrarBtn"); // NOI18N

NuevoBtn.setText("Nuevo");
NuevoBtn.setName("NuevoBtn"); // 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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILIN
G)
.addComponent(RegistrarBtn)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(90, 90, 90)
.addComponent(MasculinoOpt)
.addGap(61, 61, 61)
.addComponent(FemeninoOpt)))
.addGap(27, 27, 27)
.addComponent(NuevoBtn))
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(26, 26, 26)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G, false)
.addComponent(IdentificacionTxt)
.addComponent(NombresTxt)
.addComponent(ApellidosTxt)
.addComponent(FechaNacimientoDtc,
javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))))
.addContainerGap(51, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELI
NE)
.addComponent(jLabel1)
.addComponent(IdentificacionTxt,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

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

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELI
NE)
.addComponent(jLabel2)
.addComponent(NombresTxt,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

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

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELI
NE)
.addComponent(jLabel3)
.addComponent(ApellidosTxt,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILIN
G)
.addComponent(jLabel4)
.addComponent(FechaNacimientoDtc,
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.BASELI
NE)
.addComponent(jLabel5)
.addComponent(MasculinoOpt)
.addComponent(FemeninoOpt))
.addGap(52, 52, 52)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELI
NE)
.addComponent(RegistrarBtn)
.addComponent(NuevoBtn))
.addContainerGap(53, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

// Variables declaration - do not modify


public javax.swing.JTextField ApellidosTxt;
public com.toedter.calendar.JDateChooser FechaNacimientoDtc;
public javax.swing.JRadioButton FemeninoOpt;
public javax.swing.JTextField IdentificacionTxt;
public javax.swing.JRadioButton MasculinoOpt;
public javax.swing.JTextField NombresTxt;
public javax.swing.JButton NuevoBtn;
public javax.swing.JButton RegistrarBtn;
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;
// End of variables declaration

private void initComponents() {


throw new UnsupportedOperationException("Not supported yet."); //To change
body of generated methods, choose Tools | Templates.
}
}

SESION 6: ACCEDIENTO A LA BASE DE DATOS CON JDBC:


CONEXIÓN:
package recurso;

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

public class Conexion {


private String driver, url, ip, bd, usr, pass;
private Connection conexion;
public Conexion(String ip, String bd, String usr, String pass)
{
driver = "oracle.jdbc.driver.oracleDriver";
this.bd = bd;
this.usr =usr;
this.pass = pass;
url = "jdbc:oracle:thin:@" + ip + ":1521:" + bd;
try
{
Class.forName(driver).newInstance();
conexion = DriverManager.getConnection(url, usr, pass);

}
catch (Exception exc)
{
JOptionPane.showMessageDialog(null, "error de conexion con la
base de datos");

}
}
public Connection getConexion()
{
return conexion;
}
public Connection CerrarConexion() throws SQLException
{
conexion.close();
conexion = null;
return conexion;

}
}

SESION 7: ACCEDIENDO A LA BASE DE DATOS CON JPA:


package modelo;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "PACIENTES")
@NamedQueries({
@NamedQuery(name = "Pacientes.findAll", query = "SELECT p FROM Pacientes
p")})
public class Pacientes implements Serializable {

private static final long serialVersionUID = 1L;


@Id
@Basic(optional = false)
@Column(name = "PACIDENTIFICACION")
private String pacidentificacion;
@Column(name = "PACNOMBRES")
private String pacnombres;
@Basic(optional = false)
@Column(name = "PACAPELLIDOS")
private String pacapellidos;
@Column(name = "PACFECHANACIMIENTO")
@Temporal(TemporalType.TIMESTAMP)
private Date pacfechanacimiento;
@Column(name = "PACSEXO")
private Character pacsexo;

public Pacientes() {
}

public Pacientes(String pacidentificacion) {


this.pacidentificacion = pacidentificacion;
}

public Pacientes(String pacidentificacion, String pacapellidos) {


this.pacidentificacion = pacidentificacion;
this.pacapellidos = pacapellidos;
}

public String getPacidentificacion() {


return pacidentificacion;
}

public void setPacidentificacion(String pacidentificacion) {


this.pacidentificacion = pacidentificacion;
}
public String getPacnombres() {
return pacnombres;
}

public void setPacnombres(String pacnombres) {


this.pacnombres = pacnombres;
}

public String getPacapellidos() {


return pacapellidos;
}

public void setPacapellidos(String pacapellidos) {


this.pacapellidos = pacapellidos;
}

public Date getPacfechanacimiento() {


return pacfechanacimiento;
}

public void setPacfechanacimiento(Date pacfechanacimiento) {


this.pacfechanacimiento = pacfechanacimiento;
}

public Character getPacsexo() {


return pacsexo;
}

public void setPacsexo(Character pacsexo) {


this.pacsexo = pacsexo;
}

@Override
public int hashCode() {
int hash = 0;
hash += (pacidentificacion != null ? pacidentificacion.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Pacientes)) {
return false;
}
Pacientes other = (Pacientes) object;
if ((this.pacidentificacion == null && other.pacidentificacion != null) ||
(this.pacidentificacion != null &&
!this.pacidentificacion.equals(other.pacidentificacion))) {
return false;
}
return true;
}

@Override
public String toString() {
return "modelo.Pacientes[ pacidentificacion=" + pacidentificacion + " ]";
}

}
PACIENTESJPACONTROLLER:
package modelo;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import modelo.exceptions.NonexistentEntityException;
import modelo.exceptions.PreexistingEntityException;

public class PacientesJpaController implements Serializable {

public PacientesJpaController(EntityManagerFactory emf) {


this.emf = emf;
}
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {


return emf.createEntityManager();
}

public void create(Pacientes pacientes) throws PreexistingEntityException,


Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(pacientes);
em.getTransaction().commit();
} catch (Exception ex) {
if (findPacientes(pacientes.getPacidentificacion()) != null) {
throw new PreexistingEntityException("Pacientes " + pacientes + " already
exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}

public void edit(Pacientes pacientes) throws NonexistentEntityException,


Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
pacientes = em.merge(pacientes);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
String id = pacientes.getPacidentificacion();
if (findPacientes(id) == null) {
throw new NonexistentEntityException("The pacientes with id " + id + "
no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}

public void destroy(String id) throws NonexistentEntityException {


EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Pacientes pacientes;
try {
pacientes = em.getReference(Pacientes.class, id);
pacientes.getPacidentificacion();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The pacientes with id " + id + " no
longer exists.", enfe);
}
em.remove(pacientes);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}

public List<Pacientes> findPacientesEntities() {


return findPacientesEntities(true, -1, -1);
}

public List<Pacientes> findPacientesEntities(int maxResults, int firstResult) {


return findPacientesEntities(false, maxResults, firstResult);
}

private List<Pacientes> findPacientesEntities(boolean all, int maxResults, int


firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Pacientes.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}

public Pacientes findPacientes(String id) {


EntityManager em = getEntityManager();
try {
return em.find(Pacientes.class, id);
} finally {
em.close();
}
}

public int getPacientesCount() {


EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Pacientes> rt = cq.from(Pacientes.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}

PACIENTE CONTROL:
package Controlador;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;
import modelo.exceptions.PreexistingEntityException;

public class PacienteControl implements ActionListener


{

vista.RegPacienteInternalFrame pacienteVista;
modelo.Pacientes pacienteModelo;
modelo.PacientesJpaController gestorPacienteModelo;

public PacienteControl(vista.RegPacienteInternalFrame pacienteVista)


{
this.pacienteVista=pacienteVista;
EntityManagerFactory emf=
Persistence.createEntityManagerFactory("ProyectoCitasPU");
gestorPacienteModelo = new modelo.PacientesJpaController(emf);

}
public void actionPerformedd(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/yyyy");
String
fechaNacimiento=formato.format(pacienteVista.FechaNacimientoDtc.getDate());
char sexo='0';

if(pacienteVista.MasculinoOpt.isSelected())
sexo='m';
else
sexo='f';

pacienteModelo= new modelo.Pacientes();


pacienteModelo.setPacidentificacion(identificacion);
pacienteModelo.setPacapellidos(apellidos);
pacienteModelo.setPacnombres(nombres);
pacienteModelo.setPacfechanacimiento(new Date(fechaNacimiento));
pacienteModelo.setPacsexo(sexo);
try
{

gestorPacienteModelo.create(pacienteModelo);
JOptionPane.showMessageDialog(pacienteVista, "Paciente registrado
correctamente");

}
catch (PreexistingEntityException ex)
{
JOptionPane.showMessageDialog(pacienteVista, "El paciente ya existe");
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(pacienteVista, ex.getMessage());
}
}
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();

@Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet."); //To change
body of generated methods, choose Tools | Templates.
}

GESTOR PACIENTE CONTROL:


package Controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class GestorPacienteControl implements ActionListener{

modelo.PacientesJpaController pacientesModelo;
vista.ConsPacienteInternalFrame consultarPacienteVista;

public GestorPacienteControl(vista.ConsPacienteInternalFrame
consultarPacienteVista)
{
this.consultarPacienteVista=consultarPacienteVista;
EntityManagerFactory emf=
Persistence.createEntityManagerFactory("ProyectoCitasPU");
pacientesModelo=new modelo.PacientesJpaController(emf);

}
@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;
List<modelo.Pacientes> pacientes=pacientesModelo.findPacientesEntities();
for(modelo.Pacientes p:pacientes)
{
switch(parametro)
{
case 1: if (p.getPacidentificacion().equals(valor))
mostrarEnTabla(p);
break;
case 2: if (p.getPacnombres().equals(valor))
mostrarEnTabla(p);
break;
case 3: if (p.getPacapellidos().equals(valor))
mostrarEnTabla(p);
break;
case 4: if (p.getPacsexo().equals(valor))
mostrarEnTabla(p);
break;
}
}
}
private void mostrarEnTabla(modelo.Pacientes p)
{
String registro[] = new String [5];
registro[0]=p.getPacidentificacion();
registro[1]=p.getPacnombres();
registro[2]=p.getPacapellidos();
registro[3]=p.getPacfechanacimiento().toString();
registro[4]=p.getPacsexo().toString();
consultarPacienteVista.getTableModel().addRow(registro);
consultarPacienteVista.getTableModel().fireTableDataChanged();

SESION 8: GENERANDO REPORTES IMPRESOS:

INFORME:
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.criver.OracleDriver";
String url="jdbc:oracle:thin:@Localhost:1521:XE";
try
{
Class.forName(driver).newInstance();
conexion=DriverManager.getConnection(url,"citas","citas");
}
catch (Exception ex)
{
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());

}
}

Das könnte Ihnen auch gefallen