manual tecnic sergi_subirats

56
Manual Tecnic Primerament instalarem el sistema operatiu (windows). Per veure el manual d'instalacio ho podem veure a les seguents pagina webs segons la versio: windows 7: http://www.softzone.es/manuales-software-2/instalar-windows-7-manual-de- instalacion-de-windows-7/ Windows xp: http://www.configurarequipos.com/doc317.html windows 8: http://www.softzone.es/manual-instalacion-windows-8-instalar-windows-8- paso-a-paso/ Un cop tenim el sistema operatiu instalat passarem a instalar el xamp, ens descarguem el instalador desde la pagina web: xamp Un cop descargat l'executem i seguim els pasos de la instalacio. Creacio de la base de dades: anem a: http://localhost/phpmyadmin/ a la pantalla que ens ha aparegut fem clic a l'opcio “base de datos”. Aqui introduim el nom que li volem dona a la nostra base de datos i li donem a crear: Un cop creada la seleccionem i creem les taules: aqui es poden veure les taules que tenim que crear:

Upload: sergi-subirats-cugat

Post on 28-Jan-2015

135 views

Category:

Technology


3 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Manual tecnic sergi_subirats

Manual Tecnic

Primerament instalarem el sistema operatiu (windows). Per veure el manual d'instalacio ho podem veure a les seguents pagina webs segons la versio:

– windows 7: http://www.softzone.es/manuales-software-2/instalar-windows-7-manual-de-instalacion-de-windows-7/

– Windows xp: http://www.configurarequipos.com/doc317.html – windows 8: http://www.softzone.es/manual-instalacion-windows-8-instalar-windows-8-

paso-a-paso/

Un cop tenim el sistema operatiu instalat passarem a instalar el xamp, ens descarguem el instalador desde la pagina web: xampUn cop descargat l'executem i seguim els pasos de la instalacio.

Creacio de la base de dades:

anem a: http://localhost/phpmyadmin/

a la pantalla que ens ha aparegut fem clic a l'opcio “base de datos”.

Aqui introduim el nom que li volem dona a la nostra base de datos i li donem a crear:

Un cop creada la seleccionem i creem les taules:

aqui es poden veure les taules que tenim que crear:

Page 2: Manual tecnic sergi_subirats

Taula client:

Taula client_productes: aquesta taula es creada automaticament.

Taula producte:

Taula usuari:

Page 3: Manual tecnic sergi_subirats

Instalacio del IDE de programacio (Netbeans):El descargarem desde la seguent pagina web: http://www.oracle.com/technetwork/java/javase/downloads/jdk-7-netbeans-download-432126.html?ssSourceSiteId=otnes

instalacio: http://www.youtube.com/watch?v=3GhqJyqr_4g

Un cop ja tenim tot aixo pasariem a programar l'aplicacio, iniciem el netbeans.

Crearem un nou projecte, anem a la pestanya “File---New Project...”:

Seleccionem aplicacion java:

Page 4: Manual tecnic sergi_subirats

Fiquem el nom a l'aplicacio i li diem que no volem clase main:

una volta li donem a finish ens apareix el seguent esquema de l'aplicació:

ara tenim que crear nous paquets, boto dret sobre “source packages”:

Creem 5 paquets nous amb els seguents noms:

Page 5: Manual tecnic sergi_subirats

Una volta creat aixo dintre del paquet datos crearem una nova clase java que sera en la que accedirem a la base de dades:

El seu contingut sera el seguent:

package datos;

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.swing.JOptionPane;

public class dades { private String user ="alumne"; private String password = "alumne"; private String db = "nova"; private String host = "localhost:3306/"; // String url = "jdbc:mysql://localhost:3306/testdb";

Page 6: Manual tecnic sergi_subirats

//con = DriverManager.getConnection(url, user, password);String driver = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://"+host+db;

public void establirconexio (){ try { Class.forName(driver); Connection con = DriverManager.getConnection(url,user,password); } catch (SQLException e) { System.out.println("SQL Exception: "+ e.toString()); } catch (ClassNotFoundException cE) { System.out.println("Class Not Found Exception: "+ cE.toString()); }}

public ResultSet listar (String cadena) throws SQLException{

Connection conexion = null;try{

Class.forName(driver);conexion = DriverManager.getConnection(url,user,password);

PreparedStatement obj = conexion.prepareStatement(cadena);ResultSet tbl = obj.executeQuery();

return tbl;}

catch (Exception e) {

JOptionPane.showMessageDialog(null, e.getMessage());return null; }

finally {

//conexion.close(); }}

public int ejecutar(String cadena){

try {

Class.forName(driver).newInstance();Connection conexion = DriverManager.getConnection(url, user, password);

PreparedStatement obj = conexion.prepareStatement (cadena);int rows = obj.executeUpdate();

return rows; }

catch (Exception e) {

JOptionPane.showMessageDialog(null, e.getMessage());return 0;

} }}

Page 7: Manual tecnic sergi_subirats

Al paquet negoci crearem les clases seguents:

El contingut de cadascun es el seguent:

Client.java:

package negoci;

import datos.dades;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;import javax.swing.JOptionPane;

public class Client { int id; String dni; String nom; String cognom; String adreça; String nomnode; String numcompte; String cuotamensual; String telefon; String email; private List<Producte> producte = new ArrayList<Producte>(); public String[] getDatos(){ String data[] = new String[6]; data[0]=this.dni; data[1]= this.nom; data[2]= this.cognom; data[3]=this.nomnode; data[4]= this.numcompte; data[5]= this.adreça; data[6]= this.telefon; data[8]= this.cuotamensual; data[9]= this.email; return data; }

public List<Producte> getProductes() { return producte; }

public void setProductes(List<Producte> productes) { this.producte = productes; } public int getId() { return id; }

Page 8: Manual tecnic sergi_subirats

public void setId(int id) { this.id = id; }

public String getDni() { return dni; }

public void setDni(String dni) { this.dni = dni; }

public String getNom() { return nom; }

public void setNom(String nom) { this.nom = nom; }

public String getCognom() { return cognom; }

public void setCognom(String cognom) { this.cognom = cognom; }

public String getCuotamensual() { return cuotamensual; }

public void setCuotamensual(String cuotamensual) { this.cuotamensual = cuotamensual; }

public String getTelefon() { return telefon; }

public void setTelefon(String telefon) { this.telefon = telefon; }

public String getAdreça() { return adreça; }

public void setAdreça(String adreça) { this.adreça = adreça; }

public String getNomnode() { return nomnode; }

public void setNomnode(String nomnode) { this.nomnode = nomnode; }

Page 9: Manual tecnic sergi_subirats

public String getEmail() { return email; }

public void setEmail(String email) { this.email = email; }

public String getNumcompte() { return numcompte; }

public void setNumcompte(String numcompte) { this.numcompte = numcompte; }

public List<Producte> getProducte() { return producte; }

public void setProducte(List<Producte> producte) { this.producte = producte; } public void afegirclient (Producte producte){ this.producte.add(producte); } public ArrayList<Client> recuperarclient(){

ArrayList lista = new ArrayList(); try {

dades obj = new dades();ResultSet tabla = obj.listar ("select * from client; ");Client client;while (tabla.next()){

client = new Client();client.setEmail(tabla.getString ("email"));lista.add(client);

} }catch(Exception e){

JOptionPane.showMessageDialog(null, e.getMessage());return null;

}return lista;

}}

Producte.java:

package negoci;

import java.sql.ResultSet;

Page 10: Manual tecnic sergi_subirats

import java.text.DecimalFormat;import java.util.ArrayList;import javax.swing.JOptionPane;import org.hibernate.Query;import org.hibernate.classic.Session;import persistencia.HibernateUtil;

public class Producte { private int id; private String nom; private double preu; private String foto; private String codi; private boolean compra;

public Producte() { }

public int getId() { return id; }

public void setId(int id) { this.id = id; }

public String getNom() { return nom; }

public void setNom(String nom) { this.nom = nom; }

public double getPreu() { return preu; }

public void setPreu(double preu) { this.preu = preu; }

public boolean iscompra() { return compra; }

public void setcompra(boolean compra) { this.compra = compra; }

public String getFoto() { return foto; }

public void setFoto(String foto) { this.foto = foto; }

public boolean isCompra() { return compra; }

public void setCompra(boolean compra) {

Page 11: Manual tecnic sergi_subirats

this.compra = compra; }

public String getCodi() { return codi; }

public void setCodi(String codi) { this.codi = codi; }

public String Redondear(double numero){ DecimalFormat decimalformat = new DecimalFormat("#.##"); return decimalformat.format(numero); }}

Usuari.java:

package negoci;

import datos.dades;import java.io.IOException;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import javax.swing.JOptionPane;

public class Usuari { int id; String usuari; String password; String tipus;

public Usuari() { } @Override public String toString() { return usuari; }

public Usuari(int id, String usuari, String password, String tipus) { this.id = id; this.usuari = usuari; this.password = password; this.tipus = tipus; }

public int getId() { return id; }

public void setId(int id) { this.id = id; }

public String getUsuari() { return usuari; }

Page 12: Manual tecnic sergi_subirats

public void setUsuari(String usuari) { this.usuari = usuari; }

public String getPassword() { return password; }

public void setPassword(String password) { this.password = password; }

public String getTipus() { return tipus; }

public void setTipus(String tipus) { this.tipus = tipus; } public boolean validarUsuario(String user, String pass) throws IOException, SQLException{ dades obj = new dades(); { ResultSet tabla = obj.listar ("select * from usuari"); ArrayList lista = new ArrayList(); login login = new login (); while (tabla.next()){ if (user.equalsIgnoreCase(tabla.getString("usuari")) && password.equals(tabla.getString("password"))){ login.setUsuari(tabla.getString("usuari")); login.setPassword(tabla.getString("password")); login.setTipus(tabla.getString("tipus")); lista.add(login); return true; } } } return false;

} public login recuperarusuari(String user, String pass, String tipus){

login login = null; try { dades obj = new dades();

ResultSet tabla = obj.listar ("select * from usuari where usuari='"+user+"' and password='"+pass+"'; ");

while (tabla.next()){

login = new login ();login.setUsuari(tabla.getString ("usuari"));login.setPassword(tabla.getString ("password"));

login.setTipus(tabla.getString("tipus"));

}

Page 13: Manual tecnic sergi_subirats

}catch(Exception e){

JOptionPane.showMessageDialog(null, e.getMessage());return null;

} return login; } public ArrayList<login> recuperarlogin(){

ArrayList lista = new ArrayList(); try {

dades obj = new dades();ResultSet tabla = obj.listar ("select * from usuari; ");login login;while (tabla.next()){

login = new login ();login.setUsuari(tabla.getString ("usuari"));login.setPassword(tabla.getString ("password"));

login.setTipus(tabla.getString ("tipus"));

lista.add(login);}

}catch(Exception e){

JOptionPane.showMessageDialog(null, e.getMessage());return null;

}return lista;

} }

login.java:

package negoci;

import datos.dades;import java.io.IOException;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import javax.swing.JOptionPane;import javax.xml.bind.ParseConversionEvent;

/** * * @author Administrador */public class login { private String usuari; private String password; private String tipus;

Page 14: Manual tecnic sergi_subirats

public login() { } public login (String usuari){ this.usuari = usuari; }

public login(String usuari, String password, String tipus) { this.usuari = usuari; this.password = password; this.tipus = tipus; } @Override public String toString() { return usuari; }

public String getPassword() { return password; }

public void setPassword(String password) { this.password = password; }

public String getUsuari() { return usuari; }

public void setUsuari(String usuari) { this.usuari = usuari; }

public String getTipus() { return tipus; }

public void setTipus(String tipus) { this.tipus = tipus; }

Una volta tenim totes aquestes clases copiades veurem que ens apareix un error a la clase Producte.java:

Page 15: Manual tecnic sergi_subirats

Si l'obrim i veiem el error podrem veure que es perque ens fa falta una llibreria (hibernate):

Per poder afegir aquesta llibreria primerament ens la tenim que descarga desde la seguent pagina web: https://skydrive.live.com/#cid=D30581FF3CFC09DF&id=D30581FF3CFC09DF%21136

Descomprimim el fitxer que acabem de descarga.

Una volta descomprimit anem al netbeans i on posa libraries cliquem amb el boto dret i li donem a add Jar/Folder:

Busquem la carpeta que acabem de descomprimir i obrim tots els jar que hi ham:

Page 16: Manual tecnic sergi_subirats

Com podem veure s'ha solucionat un dels tres errors que teniem. Per poder solucionar els altres dos falta crear clases que crearem a continuacio.

A continuacio al paquet persistencia crearem la seguent clase i els seguents fitxers xml:

Client.hbm.xml:

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="negoci.Client" table="CLIENT"> <id name="id" column="ID_CLIENT"> <generator class="identity" /> </id> <property name="dni" /> <property name="nom" /> <property name="cognom" /> <property name="adreça" /> <property name="nomnode" /> <property name="numcompte" /> <property name="cuotamensual" /> <property name="telefon" /> <property name="email" /> <list name="productes" table="CLIENT_PRODUCTES" cascade="none" > <key column="ID_CLIENT" /> <list-index column="ORDEN" /> <many-to-many class="negoci.Producte" column="ID_PRODUCTE" /> </list> </class></hibernate-mapping>

HibernateUtil.java:

package persistencia;

import org.hibernate.HibernateException;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;

public class HibernateUtil { private static final SessionFactory sessionFactory; static{ try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (HibernateException he) { System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he); throw new ExceptionInInitializerError(he); } } public static SessionFactory getSessionFactory(){

Page 17: Manual tecnic sergi_subirats

return sessionFactory;} }

Producte.hbm.xml:

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="negoci.Producte" table="PRODUCTE"> <id name="id" column="ID_PRODUCTE"> <generator class="identity" /> </id> <property name="codi" /> <property name="nom" /> <property name="foto" /> <property name="preu" /> <property name="compra" /> </class></hibernate-mapping>

Usuari.hbm.xml:

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="negoci.Usuari" table="USUARI"> <id name="id" column="ID_USUARI"> <generator class="identity" /> </id> <property name="usuari" /> <property name="password" /> <property name="tipus" /> </class></hibernate-mapping>

Com podem veure a la clase negocio.Producte s'ha solucionat un altre error:

Page 18: Manual tecnic sergi_subirats

Seguidament crearem un nou fitxer xml anomenat “hibernate.cfg.xml” al arrel del programa:Com es pot veure es crear un nou paquet de forma automatica.

De moment el import de la classe Producte.java que ens esta donan error el comentarem:

Un cop tenim tot aixo passarem a la creacio dels formularis:

Per crear formularis cliquem amb el boto dret del ratoli sobre el paquet persistenica i seleccionem l'opcio “ New----JFrame form...”:

Introduim el nom del formulari

Page 19: Manual tecnic sergi_subirats

1- formulari: Formulari de login

Per crear el formulari farem servir el seguent: El formulari quedara de la seguent manera:

Per donar-li nom als controls clicarem amb el boto dret sobre ells i seleccionarem l'opcio “Properties”:

Page 20: Manual tecnic sergi_subirats
Page 21: Manual tecnic sergi_subirats

Anirem a la pestanya Code i a la segona opcio ficarem el nom:

Page 22: Manual tecnic sergi_subirats

Un cop tenim el formulari creat passarem a la part de codi:

package presentacio;

import datos.dades;import java.io.IOException;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.DefaultComboBoxModel;import javax.swing.JOptionPane;import negoci.Client;import negoci.Usuari;import negoci.login;import org.hibernate.Query;import org.hibernate.classic.Session;import persistencia.HibernateUtil;

/** *

Page 23: Manual tecnic sergi_subirats

* @author Administrador */public class FormLogin extends javax.swing.JFrame {public boolean correcte = false; /** * Creates new form forlogin */ public FormLogin() { initComponents(); inicialitzarform(); cargarbox(); } public void inicialitzarform(){ this.setTitle("Login"); this.setSize(330, 200); this.setLocationRelativeTo(null); this.setResizable(false); this.setVisible(true); }

private void cargarbox (){ Usuari prova = new Usuari(); ArrayList<login> lista = prova.recuperarlogin(); for (int x=0;x<lista.size();x++){ login obj = new login(lista.get(x).getUsuari()); cmblogin.addItem(obj); } } /** * 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") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() {

jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); btnok = new javax.swing.JButton(); btnCancelar = new javax.swing.JButton(); txtpassword = new javax.swing.JPasswordField(); cmblogin = new javax.swing.JComboBox(); lblerror = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("Usuari:");

jLabel2.setText("Password:");

btnok.setText("OK"); btnok.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnokActionPerformed(evt); } });

btnCancelar.setText("Cancelar"); btnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelarActionPerformed(evt); } });

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup(

Page 24: Manual tecnic sergi_subirats

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnok) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnCancelar)) .addComponent(txtpassword) .addComponent(cmblogin, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(lblerror, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(31, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(32, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(cmblogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(txtpassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnok) .addComponent(btnCancelar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblerror, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) );

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) );

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

private void btnokActionPerformed(java.awt.event.ActionEvent evt) { Usuari obj = new Usuari(); FormClient form = new FormClient(); dades prova = new dades(); obj.setUsuari(cmblogin.getSelectedItem().toString()); obj.setPassword(txtpassword.getText());

Page 25: Manual tecnic sergi_subirats

login permisos; if (obj.getUsuari().length() > 0 && obj.getPassword().length() > 0 ){ try { try { if(obj.validarUsuario(obj.getUsuari(), obj.getPassword())) { permisos = obj.recuperarusuari(obj.getUsuari(), obj.getPassword(), obj.getTipus()); form.txtusuari.setText(obj.getUsuari()); String nomusuari = obj.getUsuari(); Session st = HibernateUtil.getSessionFactory().openSession(); ResultSet Query = prova.listar("Select tipus from Usuari where usuari='"+obj.getUsuari()+"'"); Usuari usuari = null;

while (Query.next()){

usuari = new Usuari(); usuari.setTipus(Query.getString("tipus")); form.txttipus.setText(usuari.getTipus()); } String tipususuari = usuari.getTipus().toString(); form.cargarPermisos(permisos, nomusuari, tipususuari); st.close(); form.inicialitzaform(); form.setVisible(true); dispose(); } else{ JOptionPane.showMessageDialog(null, "contraseña no valida."); txtpassword.setText(""); } } catch (SQLException ex) { Logger.getLogger(FormLogin.class.getName()).log(Level.SEVERE, null, ex); lblerror.setText("No hi ha connexió a la BD."); } } catch (IOException ex) { Logger.getLogger(FormLogin.class.getName()).log(Level.SEVERE, null, ex); } } }

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); }

/** * @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(FormLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

Page 26: Manual tecnic sergi_subirats

} catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormLogin.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 FormLogin().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnCancelar; private javax.swing.JButton btnok; private javax.swing.JComboBox cmblogin; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JLabel lblerror; private javax.swing.JPasswordField txtpassword; // End of variables declaration }

2- formulari: Formulari dels clients

Page 27: Manual tecnic sergi_subirats

El quadre que es veu en blanc te el nom de “txttipus”.

Contindra el seguent codi:

package presentacio;

import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;import com.sun.jndi.cosnaming.IiopUrl.Address;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.Properties;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;import javax.swing.table.DefaultTableModel;import negoci.Client;import negoci.Usuari;import negoci.login;import org.hibernate.classic.Session;import persistencia.HibernateUtil;import sun.rmi.transport.Transport;

/** * * @author Administrador */public class FormClient extends javax.swing.JFrame { static public Client client1 = new Client(); private login permisosClient; private String nomusuari;

Page 28: Manual tecnic sergi_subirats

private String tipususuari; /** * Creates new form FormClient */ public FormClient() { initComponents(); inicialitzaform(); cargarTablaClients(); btneliminar.setEnabled(false); } public void inicialitzaform (){ setResizable(false); this.setTitle("Formulari client"); setSize(900, 550); setLocationRelativeTo(null); valores(); txttipus.setVisible(false); } public void afegirclient(){ client1.setDni(txtdni.getText()); client1.setNom(txtnom.getText()); client1.setCognom(txtcognoms.getText()); client1.setAdreça(txtadreça.getText()); client1.setEmail(txtemail.getText()); client1.setTelefon(txttelefon.getText()); client1.setNomnode(txtnomnode.getText()); client1.setCuotamensual(txtcuota.getText()); client1.setNumcompte(txtnumcompte.getText()); }

public void cargarPermisos(login permisos, String nomusuari, String tipususuari) throws SQLException{ txtusuari.setText(nomusuari); String tipus = txttipus.getText(); txttipus.setText(tipus); tipususuari = tipus; this.nomusuari = nomusuari; this.tipususuari = tipususuari; permisosClient = permisos; if ("administrador".equals(this.tipususuari)){ btnafegir.setVisible(true); btneliminar.setVisible(true); } else{ btnafegir.setVisible(false); btneliminar.setVisible(false); btncorreu.setVisible(false); } } public void valores (){ if (!client1.toString().equals("")){ txtnomnode.setText(client1.getNomnode()); txtcognoms.setText(client1.getCognom()); txtadreça.setText(client1.getAdreça()); txtdni.setText(client1.getDni()); txtemail.setText(client1.getEmail()); txtnumcompte.setText(client1.getNumcompte()); txtcuota.setText(client1.getCuotamensual()); txtnom.setText(client1.getNom()); txttelefon.setText(client1.getTelefon()); } }

Page 29: Manual tecnic sergi_subirats

public void cargarTablaClients(){ DefaultTableModel modelo = new DefaultTableModel(){ @Override public boolean isCellEditable (int row, int column) {

return false;}

}; Session st = HibernateUtil.getSessionFactory().openSession(); List<Client> lista = (List<Client>)st.createQuery("From Client").list(); modelo.addColumn("id"); modelo.addColumn("DNI"); modelo.addColumn("Nom"); modelo.addColumn("Cognoms"); modelo.addColumn("Adreça"); modelo.addColumn("nom_node"); modelo.addColumn("num_compte"); modelo.addColumn("cuota_mensual"); modelo.addColumn("Telefon"); modelo.addColumn("Email"); modelo.setRowCount(lista.size()); int i = 0; for(Client x : lista){ modelo.setValueAt(x.getId(), i, 0); modelo.setValueAt(x.getDni(), i, 1); modelo.setValueAt(x.getNom(), i, 2); modelo.setValueAt(x.getCognom(), i, 3); modelo.setValueAt(x.getAdreça(), i, 4); modelo.setValueAt(x.getNomnode(), i, 5); modelo.setValueAt(x.getNumcompte(), i, 6); modelo.setValueAt(x.getCuotamensual(), i, 7); modelo.setValueAt(x.getTelefon(), i, 8); modelo.setValueAt(x.getEmail(), i, 9); i++; } tblclients.setModel(modelo); tblclients.getColumnModel().getColumn(0).setMaxWidth(0); tblclients.getColumnModel().getColumn(0).setMinWidth(0); tblclients.getColumnModel().getColumn(0).setPreferredWidth(0); tblclients.getColumnModel().getColumn(0).setResizable(false); st.close(); }

public void eliminaclient(){ int fila = tblclients.getSelectedRow(); Session sesion = HibernateUtil.getSessionFactory().openSession(); sesion.beginTransaction(); Client obj=null; int id =(Integer) tblclients.getValueAt(fila, 0); obj = (Client) sesion.get(Client.class, id); sesion.delete(obj); sesion.getTransaction().commit(); sesion.close(); cargarTablaClients(); } public void rellenavalors(){ Client obj = new Client();

Page 30: Manual tecnic sergi_subirats

int columna=1; int fila = this.tblclients.getSelectedRow(); //fila seleccionada txtdni.setText(tblclients.getValueAt(fila, columna++).toString()); txtnom.setText(tblclients.getValueAt(fila, columna++).toString()); txtcognoms.setText(tblclients.getValueAt(fila, columna++).toString()); txtadreça.setText(tblclients.getValueAt(fila, columna++).toString()); txtnomnode.setText(tblclients.getValueAt(fila, columna++).toString()); txtnumcompte.setText(tblclients.getValueAt(fila, columna++).toString()); txtcuota.setText(tblclients.getValueAt(fila, columna++).toString()); txttelefon.setText(tblclients.getValueAt(fila, columna++).toString()); txtemail.setText(tblclients.getValueAt(fila, columna++).toString()); } public void limpia (){ txtdni.setText(""); txtnom.setText(""); txtcognoms.setText(""); txtadreça.setText(""); txtnomnode.setText(""); txtnumcompte.setText(""); txtcuota.setText(""); txttelefon.setText(""); txtemail.setText(""); } /** * 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") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() {

grupSexe = new javax.swing.ButtonGroup(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); txtdni = new javax.swing.JTextField(); txtnom = new javax.swing.JTextField(); txtcognoms = new javax.swing.JTextField(); txtadreça = new javax.swing.JTextField(); txtcuota = new javax.swing.JTextField(); txtnomnode = new javax.swing.JTextField(); txtemail = new javax.swing.JTextField(); txttelefon = new javax.swing.JTextField(); btncancelar = new javax.swing.JButton(); btnseguent = new javax.swing.JButton(); btneliminar = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); tblclients = new javax.swing.JTable(); btnafegir = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); txtnumcompte = new javax.swing.JTextField(); txtusuari = new javax.swing.JLabel(); txttipus = new javax.swing.JTextField(); btnsessio = new javax.swing.JButton(); jLabel11 = new javax.swing.JLabel(); btncorreu = new javax.swing.JButton();

Page 31: Manual tecnic sergi_subirats

jTable1.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" } )); jScrollPane1.setViewportView(jTable1);

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 48)); // NOI18N jLabel1.setText("Datos del client");

jLabel2.setText("DNI: ");

jLabel3.setText("Nom:");

jLabel4.setText("Cognoms:");

jLabel6.setText("Direccio:");

jLabel7.setText("Cuota mensual");

jLabel8.setText("Nom del Node");

jLabel9.setText("Email:");

jLabel10.setText("Telefon:");

btncancelar.setText("CANCELAR"); btncancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btncancelarActionPerformed(evt); } });

btnseguent.setText("SEGUENT"); btnseguent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnseguentActionPerformed(evt); } });

btneliminar.setText("Eliminar"); btneliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btneliminarActionPerformed(evt); } });

tblclients.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" } )); tblclients.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblclientsMouseClicked(evt);

Page 32: Manual tecnic sergi_subirats

} }); jScrollPane3.setViewportView(tblclients);

btnafegir.setText("Afegir"); btnafegir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnafegirActionPerformed(evt); } });

jLabel5.setText("Numero de compte:");

btnsessio.setText("Cerrar session"); btnsessio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnsessioActionPerformed(evt); } });

jLabel11.setText("Usuari: ");

btncorreu.setText("Email"); btncorreu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btncorreuActionPerformed(evt); } });

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btncancelar) .addGap(18, 18, 18) .addComponent(btnseguent) .addGap(102, 102, 102)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(18, 18, 18) .addComponent(txtnumcompte, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel6)) .addGap(64, 64, 64) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtnom, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE) .addComponent(txtcognoms, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtadreça) .addComponent(txtdni)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jLabel9) .addComponent(jLabel10)) .addGap(23, 23, 23)

Page 33: Manual tecnic sergi_subirats

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtemail, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE) .addComponent(txttelefon) .addComponent(txtnomnode))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel7) .addGap(18, 18, 18) .addComponent(txtcuota, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 142, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(txttipus, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane3)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(btneliminar) .addGap(18, 18, 18) .addComponent(btnafegir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btncorreu)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(125, 125, 125) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(btnsessio) .addGap(14, 14, 14) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtusuari, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(29, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(btnsessio) .addComponent(txtusuari, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)) .addGap(16, 16, 16) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtdni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtnom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(txtcognoms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

Page 34: Manual tecnic sergi_subirats

.addComponent(jLabel8) .addComponent(txtnomnode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(txtemail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(txttelefon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(11, 11, 11) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(txtcuota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6) .addComponent(txtadreça, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtnumcompte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(txttipus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnseguent) .addComponent(btncancelar)) .addGap(18, 18, 18) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btneliminar) .addComponent(btnafegir) .addComponent(btncorreu)) .addGap(95, 95, 95)) );

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) );

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

private void btncancelarActionPerformed(java.awt.event.ActionEvent evt) { int eleccion = JOptionPane.showConfirmDialog(null, "Desea salir?","sortir",JOptionPane.YES_NO_OPTION); if ( eleccion == 0) { System.exit(0); } }

Page 35: Manual tecnic sergi_subirats

private void btnseguentActionPerformed(java.awt.event.ActionEvent evt) { if (!txtdni.getText().equals("") && !txtnom.getText().equals("") && !txtcognoms.getText().equals("")){ afegirclient(); FormProducte obj = new FormProducte(); try { obj.cargarPermisos(permisosClient, nomusuari, tipususuari); } catch (SQLException ex) { Logger.getLogger(FormClient.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(tipususuari); this.setVisible(false); obj.inicialitzaform(); } else { JOptionPane.showMessageDialog(null, "Introdueix tots els camps"); } }

private void btneliminarActionPerformed(java.awt.event.ActionEvent evt) { if (JOptionPane.showConfirmDialog(rootPane, "¿Desea realmente borrar el cliente?", "Borrar cliente", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) eliminaclient(); }

private void tblclientsMouseClicked(java.awt.event.MouseEvent evt) { btneliminar.setEnabled(true); if (evt.getClickCount()==2){ rellenavalors(); } }

private void btnafegirActionPerformed(java.awt.event.ActionEvent evt) { if (!txtadreça.getText().equals("") && !txtcognoms.getText().equals("") && !txtcuota.getText().equals("") && !txtdni.getText().equals("") && !txtemail.getText().equals("") && !txtnom.getText().equals("") && !txtnomnode.getText().equals("") && !txtnumcompte.getText().equals("") && !txttelefon.getText().equals("") ){ afegirclient(); Session sesion = HibernateUtil.getSessionFactory().openSession(); sesion.beginTransaction(); sesion.save(client1); sesion.getTransaction().commit(); sesion.close(); limpia(); cargarTablaClients(); } }

private void btnsessioActionPerformed(java.awt.event.ActionEvent evt) { dispose(); FormLogin login = new FormLogin(); login.inicialitzarform(); login.setVisible(true); }

private void btncorreuActionPerformed(java.awt.event.ActionEvent evt) { FormEmail email = new FormEmail(); email.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 */

Page 36: Manual tecnic sergi_subirats

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(FormClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormClient.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 FormClient().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnafegir; private javax.swing.JButton btncancelar; private javax.swing.JButton btncorreu; private javax.swing.JButton btneliminar; private javax.swing.JButton btnseguent; private javax.swing.JButton btnsessio; private javax.swing.ButtonGroup grupSexe; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; 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.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTable jTable1; private javax.swing.JTable tblclients; private javax.swing.JTextField txtadreça; private javax.swing.JTextField txtcognoms; private javax.swing.JTextField txtcuota; private javax.swing.JTextField txtdni; private javax.swing.JTextField txtemail; private javax.swing.JTextField txtnom; private javax.swing.JTextField txtnomnode; private javax.swing.JTextField txtnumcompte; private javax.swing.JTextField txttelefon; public javax.swing.JTextField txttipus; public javax.swing.JLabel txtusuari; // End of variables declaration }

3- formulari: Formulari dels productes

Page 37: Manual tecnic sergi_subirats

Codi del formulari:

package presentacio;

import java.awt.Image;import java.awt.Toolkit;import java.net.URL;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.table.DefaultTableModel;import negoci.Client;import negoci.Producte;import negoci.login;import org.hibernate.classic.Session;import persistencia.HibernateUtil;

/** *

Page 38: Manual tecnic sergi_subirats

* @author Administrador */public class FormProducte extends javax.swing.JFrame { static public Client client = FormClient.client1; static public Client client1 = client; static public Producte producte = new Producte(); static public List<Producte> lista = new ArrayList<>(); static public List<Producte> lista1 = new ArrayList<>(); private login permisosClient; private String nomusuari; private String tipususuari; private String rutafoto = "fotosproductes/"; /** * Creates new form FormProducte */ public FormProducte(login permisos,String nomusuari, String tipususuari) { permisosClient = permisos; this.nomusuari = nomusuari; this.tipususuari = tipususuari; initComponents(); inicialitzaform(); btneliminar.setEnabled(false); } public FormProducte() { this.setTitle("Formulari producte"); initComponents(); inicialitzaform(); btneliminar.setEnabled(false); }

public void inicialitzaform (){ setResizable(false); setSize(700, 550); setLocationRelativeTo(null); cargarTabla(); setVisible(true); } public void cargarTabla(){ DefaultTableModel modelo = new DefaultTableModel(){ @Override public Class getColumnClass(int columnIndex) {

if (columnIndex == 5 ) {return Boolean.class;

}else {

return super.getColumnClass (columnIndex);}

} public boolean isCellEditable (int row, int column) { if(column==5){ return true; }

return false;}

}; Session st = HibernateUtil.getSessionFactory().openSession(); lista = (List<Producte>)st.createQuery("From Producte").list();

Page 39: Manual tecnic sergi_subirats

modelo.addColumn("id"); modelo.addColumn("codi"); modelo.addColumn("nom"); modelo.addColumn("preu"); modelo.addColumn("foto"); modelo.addColumn("compra"); modelo.setRowCount(lista.size()); int i = 0; for(Producte x : lista){ modelo.setValueAt(x.getId(), i, 0); modelo.setValueAt(x.getCodi(), i, 1); modelo.setValueAt(x.getNom(), i, 2); modelo.setValueAt(x.getPreu(), i, 3); modelo.setValueAt(x.getFoto(), i, 4); if (lista1.isEmpty()){ modelo.setValueAt(x.isCompra(), i, 5); } else{ for (Producte y : lista1){ if(x.getCodi() == null ? y.getCodi() == null : x.getCodi().equals(y.getCodi())){ modelo.setValueAt(true, i, 5); } } } i++; } this.tblproductes.setModel(modelo); tblproductes.getColumnModel().getColumn(0).setMaxWidth(0); tblproductes.getColumnModel().getColumn(0).setMinWidth(0); tblproductes.getColumnModel().getColumn(0).setPreferredWidth(0); tblproductes.getColumnModel().getColumn(0).setResizable(false); st.close(); } public void cargarPermisos(login permisos, String nomusuari, String tipususuari) throws SQLException{ FormClient obj = new FormClient(); obj.txtusuari.setText(nomusuari); this.nomusuari = nomusuari; this.tipususuari = tipususuari; permisosClient = permisos; if ("administrador".equals(tipususuari)){ btnafegir.setVisible(true); btneliminar.setVisible(true); } else{ btnafegir.setVisible(false); btneliminar.setVisible(false); txtcodi.setVisible(false); txtfoto.setVisible(false); txtnom.setVisible(false); txtpreu.setVisible(false); lblcodi.setVisible(false); lblfoto.setVisible(false); lblnom.setVisible(false); lblpreu.setVisible(false); } }

public void eliminaProducte(){ int fila = tblproductes.getSelectedRow(); Session sesion = HibernateUtil.getSessionFactory().openSession();

Page 40: Manual tecnic sergi_subirats

sesion.beginTransaction(); System.out.println(fila); Producte obj=null; int id =(Integer) tblproductes.getValueAt(fila, 0); obj = (Producte) sesion.get(Producte.class, id); sesion.delete(obj); sesion.getTransaction().commit(); sesion.close(); cargarTabla(); } public void limpia (){ txtcodi.setText(""); txtnom.setText(""); txtpreu.setText(""); txtfoto.setText(""); } public void afegirproducte(){ producte.setCodi(txtcodi.getText()); producte.setNom(txtnom.getText()); producte.setFoto(txtfoto.getText()); producte.setPreu(Float.parseFloat(txtpreu.getText())); producte.setCompra(false); } public void rellenavalors(){ Producte obj = new Producte(); int columna=1; int fila = this.tblproductes.getSelectedRow(); //fila seleccionada txtcodi.setText(tblproductes.getValueAt(fila, columna++).toString()); txtnom.setText(tblproductes.getValueAt(fila, columna++).toString()); txtpreu.setText(tblproductes.getValueAt(fila, columna++).toString()); txtfoto.setText(tblproductes.getValueAt(fila, columna++).toString()); } /** * 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") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() {

jPanel1 = new javax.swing.JPanel(); btnatras = new javax.swing.JButton(); btnseguent = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tblproductes = new javax.swing.JTable(); btneliminar = new javax.swing.JButton(); btnafegir = new javax.swing.JButton(); lblcodi = new javax.swing.JLabel(); lblnom = new javax.swing.JLabel(); lblpreu = new javax.swing.JLabel(); lblfoto = new javax.swing.JLabel(); txtcodi = new javax.swing.JTextField(); txtnom = new javax.swing.JTextField(); txtpreu = new javax.swing.JTextField(); txtfoto = new javax.swing.JTextField(); lblimagen = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

btnatras.setText("atras"); btnatras.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnatrasActionPerformed(evt);

Page 41: Manual tecnic sergi_subirats

} });

btnseguent.setText("seguent"); btnseguent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnseguentActionPerformed(evt); } });

tblproductes.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" } )); tblproductes.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblproductesMouseClicked(evt); } }); jScrollPane1.setViewportView(tblproductes);

btneliminar.setText("Eliminar"); btneliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btneliminarActionPerformed(evt); } });

btnafegir.setText("Afegir"); btnafegir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnafegirActionPerformed(evt); } });

lblcodi.setText("Codi: ");

lblnom.setText("Nom: ");

lblpreu.setText("Preu: ");

lblfoto.setText("Foto: ");

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblpreu) .addComponent(lblnom) .addComponent(lblcodi)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtpreu, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE) .addComponent(txtnom, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtcodi, javax.swing.GroupLayout.Alignment.LEADING)))

Page 42: Manual tecnic sergi_subirats

.addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lblfoto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btneliminar) .addGap(73, 73, 73) .addComponent(btnafegir)) .addComponent(txtfoto, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnatras) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnseguent) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblimagen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(27, 27, 27)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnatras) .addComponent(btnseguent)) .addGap(18, 18, 18) .addComponent(lblimagen, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblcodi) .addComponent(txtcodi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblnom) .addComponent(txtnom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblpreu) .addComponent(txtpreu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblfoto) .addComponent(txtfoto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btneliminar) .addComponent(btnafegir)))) .addGap(0, 11, Short.MAX_VALUE)) );

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

Page 43: Manual tecnic sergi_subirats

.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) );

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

private void btnafegirActionPerformed(java.awt.event.ActionEvent evt) { afegirproducte(); Session sesion = HibernateUtil.getSessionFactory().openSession(); sesion.beginTransaction(); sesion.save(producte); sesion.getTransaction().commit(); sesion.close(); limpia(); cargarTabla(); }

private void btneliminarActionPerformed(java.awt.event.ActionEvent evt) { if (JOptionPane.showConfirmDialog(rootPane, "¿Desea realmente borrar el producto?", "Borrar producto", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) eliminaProducte(); }

private void tblproductesMouseClicked(java.awt.event.MouseEvent evt) { btneliminar.setEnabled(true); Producte obj = new Producte(); int fila = this.tblproductes.getSelectedRow(); //fila seleccionada String foto = tblproductes.getValueAt(fila, 4).toString(); ImageIcon fot = new ImageIcon(rutafoto+foto+".jpg"); Icon icono = new ImageIcon(fot.getImage().getScaledInstance(lblimagen.getWidth(), lblimagen.getHeight(), Image.SCALE_DEFAULT)); lblimagen.setIcon(icono); this.repaint(); }

private void btnseguentActionPerformed(java.awt.event.ActionEvent evt) { lista1.clear(); for (int i=0; i<lista.size();i++) if (tblproductes.getValueAt(i, 5)==true){ lista1.add(lista.get(i)); } FormResumen obj = new FormResumen(permisosClient, nomusuari, tipususuari); this.setVisible(false); obj.setVisible(true);

}

private void btnatrasActionPerformed(java.awt.event.ActionEvent evt) { dispose(); FormClient obj = new FormClient(); try { obj.txtusuari.setText(nomusuari); obj.txttipus.setText(tipususuari); obj.cargarPermisos(permisosClient, nomusuari, tipususuari); } catch (SQLException ex) { Logger.getLogger(FormProducte.class.getName()).log(Level.SEVERE, null, ex); } obj.setVisible(true); }

Page 44: Manual tecnic sergi_subirats

/** * @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(FormProducte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormProducte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormProducte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormProducte.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 FormProducte().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnafegir; private javax.swing.JButton btnatras; private javax.swing.JButton btneliminar; private javax.swing.JButton btnseguent; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblcodi; private javax.swing.JLabel lblfoto; private javax.swing.JLabel lblimagen; private javax.swing.JLabel lblnom; private javax.swing.JLabel lblpreu; private javax.swing.JTable tblproductes; private javax.swing.JTextField txtcodi; private javax.swing.JTextField txtfoto; private javax.swing.JTextField txtnom; private javax.swing.JTextField txtpreu; // End of variables declaration }

4- formulari: Formulari resum

Page 45: Manual tecnic sergi_subirats

Codi:

package presentacio;

import Funcions.CrearPDF;import java.sql.SQLException;import java.text.DecimalFormat;import java.util.List;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;import javax.swing.table.DefaultTableModel;import negoci.Client;import negoci.Producte;import negoci.login;import org.hibernate.classic.Session;import persistencia.HibernateUtil;

/** * * @author Administrador */public class FormResumen extends javax.swing.JFrame {static public Client client = FormProducte.client1; List<Producte> lista = FormProducte.lista1; private login permisosClient; private String nomusuari; private String tipususuari; double IVA, hora = 10.5, preutotal,suma; /** * Creates new form FormResumen */ public FormResumen(login permisos,String nomusuari, String tipususuari) { initComponents(); this.setTitle("Formulari resum"); inicialitzaform(); recuperarclient(); cargarTabla(); minimproductes();

Page 46: Manual tecnic sergi_subirats

permisosClient = permisos; this.nomusuari = nomusuari; this.tipususuari = tipususuari; } public FormResumen() { initComponents(); inicialitzaform(); recuperarclient(); cargarTabla(); minimproductes(); }

public void inicialitzaform (){ setResizable(false); setSize(700, 550); setLocationRelativeTo(null); setVisible(true); } public void minimproductes(){ if (lista.isEmpty()){ btnfinalitzar.setEnabled(false); btnCrearPDF.setEnabled(false); lbldescripcio.setText("Has de seleccionar minim un producte"); } else{ btnfinalitzar.setEnabled(true); btnCrearPDF.setEnabled(true); mostrarpreu(); } } public void mostrarpreu (){ suma = 0; for(Producte x : lista){ suma=x.getPreu() + suma; } Producte obj = new Producte(); lbldescripcio.setText("Preu total: " +obj.Redondear(suma)+"€"); IVA = suma * 16 / 100; preutotal = IVA + hora + suma; } public void recuperarclient(){ txtresum.setText("\t"+"\t"+"DADES DEL CLIENT \n \n"); txtresum.append("NOM: "); txtresum.append(client.getNom()+"\n"); txtresum.append("COGNOMS: "); txtresum.append(client.getCognom()+"\n"); txtresum.append("DNI: "); txtresum.append(client.getDni()+"\n"); txtresum.append("DIRECCIO: "); txtresum.append(client.getAdreça()+"\n"); txtresum.append("NOM DEL NODE: "); txtresum.append(client.getNomnode()+"\n"); txtresum.append("NUMERO DE COMPTE: "); txtresum.append(client.getNumcompte()+"\n"); txtresum.append("CUOTA MENSUAL: "); txtresum.append(client.getCuotamensual()+"\n"); txtresum.append("EMAIL: "); txtresum.append(client.getEmail()+"\n"); txtresum.append("TELEFON: "); txtresum.append(client.getTelefon()+"\n"); } public void cargarTabla(){ DefaultTableModel modelo = new DefaultTableModel(){

Page 47: Manual tecnic sergi_subirats

public boolean isCellEditable (int row, int column) {return false;

} }; Producte producte = new Producte(); modelo.addColumn("codi"); modelo.addColumn("nom"); modelo.addColumn("preu"); modelo.setRowCount(lista.size()); int i = 0; for(Producte x : lista){ modelo.setValueAt(x.getCodi(), i, 0); modelo.setValueAt(x.getNom(), i, 1); modelo.setValueAt(x.getPreu(), i, 2); i++; } this.tblresum.setModel(modelo); } public void guardarproductes(){ for (Producte x : lista){ client.afegirclient(x); } Session sesion = HibernateUtil.getSessionFactory().openSession(); sesion.beginTransaction(); sesion.save(client); sesion.getTransaction().commit(); sesion.close(); } /** * 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") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() {

jPanel1 = new javax.swing.JPanel(); btnatras = new javax.swing.JButton(); btnfinalitzar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tblresum = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); txtresum = new javax.swing.JTextArea(); lbldescripcio = new javax.swing.JLabel(); btnCrearPDF = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

btnatras.setText("Atras"); btnatras.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnatrasActionPerformed(evt); } });

btnfinalitzar.setText("Finalitzar"); btnfinalitzar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnfinalitzarActionPerformed(evt); } });

tblresum.setModel(new javax.swing.table.DefaultTableModel(

Page 48: Manual tecnic sergi_subirats

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" } )); jScrollPane1.setViewportView(tblresum);

txtresum.setColumns(20); txtresum.setRows(5); jScrollPane2.setViewportView(txtresum);

lbldescripcio.setFont(new java.awt.Font("Times New Roman", 1, 20)); // NOI18N lbldescripcio.setForeground(new java.awt.Color(204, 0, 0));

btnCrearPDF.setText("Pressupost"); btnCrearPDF.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCrearPDFActionPerformed(evt); } });

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(btnCrearPDF) .addGap(27, 27, 27) .addComponent(lbldescripcio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnatras) .addGap(18, 18, 18) .addComponent(btnfinalitzar) .addGap(14, 14, 14)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnatras) .addComponent(btnfinalitzar) .addComponent(btnCrearPDF))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(lbldescripcio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18)) );

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,

Page 49: Manual tecnic sergi_subirats

Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) );

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

private void btnatrasActionPerformed(java.awt.event.ActionEvent evt) { try { FormProducte obj = new FormProducte(); obj.cargarPermisos(permisosClient, nomusuari, tipususuari); this.setVisible(false); obj.inicialitzaform(); obj.setVisible(true); } catch (SQLException ex) { Logger.getLogger(FormResumen.class.getName()).log(Level.SEVERE, null, ex); } }

private void btnfinalitzarActionPerformed(java.awt.event.ActionEvent evt) { CrearPDF obj = new CrearPDF(); Producte pro = new Producte(); int factura = JOptionPane.showConfirmDialog(null, "Desea crear factura","sortir",JOptionPane.YES_NO_OPTION); if ( factura == 0) { //arrodonim els valors a dos decimals com a molt String preu = String.valueOf(pro.Redondear(preutotal)); String iva = String.valueOf(pro.Redondear(IVA)); String hores = String.valueOf(pro.Redondear(hora)); String Total = String.valueOf(pro.Redondear(suma)); obj.crear_PDF("Factura", "Sergi Subirats Cugat", "Factura", "", "Nom: "+client.getNom()+"\n"+ "Cognoms: "+client.getCognom()+"\n"+ "DNI: "+client.getDni()+"\n"+ "Adreça: "+client.getAdreça()+"\n"+ "Nom del node: "+client.getNomnode()+"\n"+ "Numero de compte: "+client.getNumcompte()+"\n"+ "Cuota mensual: "+client.getCuotamensual()+"\n"+ "Telefon: "+client.getTelefon()+"\n"+ "Email: "+client.getEmail()+"\n" , "Total: "+preu+"€", "FACTURA"+"\n \n", "Import IVA: "+iva+"€", "Preu/hora: "+hores+"€", "Import Total : "+Total+"€", "NOTA: Aqui falta suma el import del cabletjat segons els metros gastats" ); } int eleccion = JOptionPane.showConfirmDialog(null, "Desea Guardar los datos i finalizar?","sortir",JOptionPane.YES_NO_OPTION); if ( eleccion == 0) { guardarproductes(); System.exit(0); } }

private void btnCrearPDFActionPerformed(java.awt.event.ActionEvent evt) { CrearPDF obj = new CrearPDF(); Producte pro = new Producte(); //arrodonim els valors a dos decimals com a molt String preu = String.valueOf(pro.Redondear(preutotal)); String iva = String.valueOf(pro.Redondear(IVA)); String hores = String.valueOf(pro.Redondear(hora));

Page 50: Manual tecnic sergi_subirats

String Total = String.valueOf(pro.Redondear(suma)); obj.crear_PDF("Presupost", "Sergi Subirats Cugat", "Presupost", "", "Nom: "+client.getNom()+"\n"+ "Cognoms: "+client.getCognom()+"\n"+ "DNI: "+client.getDni()+"\n"+ "Adreça: "+client.getAdreça()+"\n"+ "Nom del node: "+client.getNomnode()+"\n"+ "Numero de compte: "+client.getNumcompte()+"\n"+ "Cuota mensual: "+client.getCuotamensual()+"\n"+ "Telefon: "+client.getTelefon()+"\n"+ "Email: "+client.getEmail()+"\n" , "Total: "+preu+"€", "PRESUPOST"+"\n \n", "Import IVA: "+iva+"€", "Preu/hora: "+hores+"€", "Import Total : "+Total+"€", "NOTA: Aqui falta suma el import del cabletjat segons els metros gastats" ); }

/** * @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(FormResumen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormResumen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormResumen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormResumen.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 FormResumen().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnCrearPDF; private javax.swing.JButton btnatras; private javax.swing.JButton btnfinalitzar; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel lbldescripcio; private javax.swing.JTable tblresum; private javax.swing.JTextArea txtresum; // End of variables declaration }

5- formulari: Formulari per enviar correus

Page 51: Manual tecnic sergi_subirats
Page 52: Manual tecnic sergi_subirats

codi:

package presentacio;

import java.util.ArrayList;import negoci.Client;import negoci.Usuari;import negoci.login;

public class FormEmail extends javax.swing.JFrame {

Funcions.Email mail = new Funcions.Email();

/** Creates new form interfaz */ public FormEmail() { initComponents(); this.setTitle("Enviar Correo"); inicialitzaform(); } public void inicialitzaform (){ setResizable(false); setSize(470, 400); setLocationRelativeTo(null); cargarbox(); } private void cargarbox (){ Client prova = new Client(); ArrayList<Client> lista = prova.recuperarclient(); for (int x=0;x<lista.size();x++){ cmbusuari.addItem(lista.get(x).getEmail()); } } public void cargarpara(){ String prova = cmbusuari.getSelectedItem().toString(); if (txtTO.getText().equals("")){ txtTO.setText(prova); } if (txtTO.getText().contains(prova)){

Page 53: Manual tecnic sergi_subirats

} else{ txtTO.setText(txtTO.getText()+", "+prova); } if (chbtodos.isSelected()==true){ Client client = new Client(); ArrayList<Client> lista = client.recuperarclient(); for (int x=0;x<lista.size();x++){ if (txtTO.getText().equals("")){ txtTO.setText(lista.get(x).getEmail()); } if (txtTO.getText().contains(lista.get(x).getEmail())){ } else{ txtTO.setText(txtTO.getText()+", "+(lista.get(x).getEmail())); } } } }

/** 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") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { java.awt.GridBagConstraints gridBagConstraints;

jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txtFROM = new javax.swing.JTextField(); txtTO = new javax.swing.JTextField(); txtSUBJECT = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtPWD = new javax.swing.JPasswordField(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); txtMESSAGE = new javax.swing.JTextArea(); cmdSEND = new javax.swing.JButton(); cmbusuari = new javax.swing.JComboBox(); btninsertar = new javax.swing.JButton(); chbtodos = new javax.swing.JCheckBox();

jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel1.setLayout(new java.awt.GridBagLayout());

jLabel1.setText("De :"); jLabel1.setAlignmentY(1.0F); jPanel1.add(jLabel1, new java.awt.GridBagConstraints());

jLabel2.setText("Para :"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(jLabel2, gridBagConstraints);

jLabel3.setText("Asunto :"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(jLabel3, gridBagConstraints);

Page 54: Manual tecnic sergi_subirats

txtFROM.setPreferredSize(new java.awt.Dimension(160, 28)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 10); jPanel1.add(txtFROM, gridBagConstraints);

txtTO.setPreferredSize(new java.awt.Dimension(390, 28)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5); jPanel1.add(txtTO, gridBagConstraints);

txtSUBJECT.setPreferredSize(new java.awt.Dimension(390, 28)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5); jPanel1.add(txtSUBJECT, gridBagConstraints);

jLabel4.setText("Password :"); jPanel1.add(jLabel4, new java.awt.GridBagConstraints());

txtPWD.setPreferredSize(new java.awt.Dimension(153, 28)); jPanel1.add(txtPWD, new java.awt.GridBagConstraints());

jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

txtMESSAGE.setColumns(20); txtMESSAGE.setRows(5); jScrollPane1.setViewportView(txtMESSAGE);

javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) );

cmdSEND.setText("Enviar"); cmdSEND.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSENDActionPerformed(evt); } });

btninsertar.setText("Insertar"); btninsertar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btninsertarActionPerformed(evt); } });

Page 55: Manual tecnic sergi_subirats

chbtodos.setText("Tots");

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.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(cmdSEND) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(chbtodos) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmbusuari, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btninsertar))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmdSEND) .addComponent(cmbusuari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btninsertar) .addComponent(chbtodos)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) );

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

private void cmdSENDActionPerformed(java.awt.event.ActionEvent evt) { mail.setFrom( this.txtFROM.getText() ); mail.setPassword( this.txtPWD.getPassword() ); mail.setTo( this.txtTO.getText() ); mail.setSubject( this.txtSUBJECT.getText() ); mail.setMessage( this.txtMESSAGE.getText() ); mail.SEND(); dispose(); }

private void btninsertarActionPerformed(java.awt.event.ActionEvent evt) { cargarpara(); chbtodos.setSelected(false); }

/** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() {

Page 56: Manual tecnic sergi_subirats

new FormEmail().setVisible(true); } }); }

// Variables declaration - do not modify private javax.swing.JButton btninsertar; private javax.swing.JCheckBox chbtodos; private javax.swing.JComboBox cmbusuari; private javax.swing.JButton cmdSEND; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtFROM; private javax.swing.JTextArea txtMESSAGE; private javax.swing.JPasswordField txtPWD; private javax.swing.JTextField txtSUBJECT; private javax.swing.JTextField txtTO; // End of variables declaration

}