feat(ch 8 & 9): added

This commit is contained in:
Rafa Muñoz
2025-02-16 19:47:41 +01:00
parent acb8877882
commit 1b2b2350f1
213 changed files with 96731 additions and 0 deletions

View File

@@ -6,5 +6,20 @@
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="src" path="src"/> <classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/jpa/javax.persistence_2.1.0.v201304241213.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/jpa/org.eclipse.persistence.jpa.modelgen_2.5.2.v20140319-9ad6abd.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/jpa/org.eclipse.persistence.jpars_2.5.2.v20140319-9ad6abd.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/moxy/com.sun.tools.xjc_2.2.0.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/moxy/com.sun.xml.bind_2.2.0.v201004141950.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/moxy/javax.activation_1.1.0.v201108011116.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/moxy/javax.mail_1.4.0.v201005080615.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/moxy/javax.xml.bind_2.2.0.v201105210648.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/moxy/javax.xml.stream_1.0.1.v201004272200.jar"/>
<classpathentry kind="lib" path="librerias/EclipseLink2.5.2/jlib/eclipselink.jar"/>
<classpathentry kind="lib" path="librerias/mongoDB-Java-driver/mongo-java-driver-3.12.12.jar"/>
<classpathentry kind="lib" path="librerias/Jackson/jackson-annotations-2.9.0.jar"/>
<classpathentry kind="lib" path="librerias/Jackson/jackson-core-2.9.5.jar"/>
<classpathentry kind="lib" path="librerias/Jackson/jackson-databind-2.9.5.jar"/>
<classpathentry kind="lib" path="librerias/Driver_MySQL_Connector_J/mysql-connector-java-8.0.19.jar"/>
<classpathentry kind="output" path="bin"/> <classpathentry kind="output" path="bin"/>
</classpath> </classpath>

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,174 @@
CREATE DATABASE IF NOT EXISTS `centroeducativo` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `centroeducativo`;
-- MySQL dump 10.13 Distrib 5.6.13, for Win32 (x86)
--
-- Host: 127.0.0.1 Database: centroeducativo
-- ------------------------------------------------------
-- Server version 5.6.16-log
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `curso`
--
DROP TABLE IF EXISTS `curso`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `curso` (
`id` int(11) NOT NULL,
`descripcion` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `curso`
--
LOCK TABLES `curso` WRITE;
/*!40000 ALTER TABLE `curso` DISABLE KEYS */;
INSERT INTO `curso` VALUES (1,'2017-18');
/*!40000 ALTER TABLE `curso` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `estudiante`
--
DROP TABLE IF EXISTS `estudiante`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `estudiante` (
`id` int(11) NOT NULL,
`nombre` varchar(150) DEFAULT NULL,
`apellido1` varchar(150) DEFAULT NULL,
`apellido2` varchar(150) DEFAULT NULL,
`dni` varchar(15) DEFAULT NULL,
`direccion` varchar(250) DEFAULT NULL,
`email` varchar(150) DEFAULT NULL,
`telefono` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `estudiante`
--
LOCK TABLES `estudiante` WRITE;
/*!40000 ALTER TABLE `estudiante` DISABLE KEYS */;
INSERT INTO `estudiante` VALUES (1,'Julio','Mármol','Mármol','14785236A','dir, 21','adsf','654785214'),(2,'Francisco','Fernández','Fernández','52874369B','dir, 24','f@f.com','741258963'),(3,'Miguel','Palacios','Fernández','58963214C','dir, 26','m@m.com','632521478');
/*!40000 ALTER TABLE `estudiante` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `materia`
--
DROP TABLE IF EXISTS `materia`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `materia` (
`id` int(11) NOT NULL,
`nombre` varchar(100) DEFAULT NULL,
`acronimo` varchar(15) DEFAULT NULL,
`curso_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_asignatura_curso1_idx` (`curso_id`),
CONSTRAINT `fk_asignatura_curso1` FOREIGN KEY (`curso_id`) REFERENCES `curso` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `materia`
--
LOCK TABLES `materia` WRITE;
/*!40000 ALTER TABLE `materia` DISABLE KEYS */;
INSERT INTO `materia` VALUES (1,'Programación','PROG',1),(2,'Lenguajes de Marcas y Sistemas de Gestión de la Información','LMSGI',1),(3,'Sistemas Informáticos','SI',1),(4,'Entornos de Desarrollo','EntDes',1),(5,'Bases de Datos','BD',1),(6,'Formación y Orientación Laboral','FOL',1);
/*!40000 ALTER TABLE `materia` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `profesor`
--
DROP TABLE IF EXISTS `profesor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `profesor` (
`id` int(11) NOT NULL,
`nombre` varchar(150) DEFAULT NULL,
`apellido1` varchar(150) DEFAULT NULL,
`apellido2` varchar(150) DEFAULT NULL,
`dni` varchar(15) DEFAULT NULL,
`direccion` varchar(250) DEFAULT NULL,
`email` varchar(150) DEFAULT NULL,
`telefono` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `profesor`
--
LOCK TABLES `profesor` WRITE;
/*!40000 ALTER TABLE `profesor` DISABLE KEYS */;
INSERT INTO `profesor` VALUES (1,'Rafael Carlos','López','Ruiz','12345678b','Su casa, 34','asdf','sdaf'),(2,'Joaquín','Molinero','Suárez','23456789B','Su casa también, 42','joaquin@joaquin.com','654789322'),(3,'Miguel Ángel','Pérez','Carmona','98765432C','Otra casa, 12','miguel@miguel.com','654147852'),(4,'Alejandro','Fernández','Fernández','47125896D','Allí, 65','alejandro@alejandro.com','658974125'),(5,'Águeda','Cuenca','Cuenca','96325874','Graná, 25','','698521478');
/*!40000 ALTER TABLE `profesor` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `valoracionmateria`
--
DROP TABLE IF EXISTS `valoracionmateria`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `valoracionmateria` (
`id` int(11) NOT NULL,
`idProfesor` int(11) NOT NULL,
`idEstudiante` int(11) NOT NULL,
`idMateria` int(11) NOT NULL,
`valoracion` float DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_asignatura_profesor_idx` (`idProfesor`),
KEY `fk_asignatura_estudiante1_idx` (`idEstudiante`),
KEY `fk_asignatura_asignatura1_idx` (`idMateria`),
CONSTRAINT `fk_asignatura_asignatura1` FOREIGN KEY (`idMateria`) REFERENCES `materia` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_asignatura_estudiante1` FOREIGN KEY (`idEstudiante`) REFERENCES `estudiante` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_asignatura_profesor` FOREIGN KEY (`idProfesor`) REFERENCES `profesor` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `valoracionmateria`
--
LOCK TABLES `valoracionmateria` WRITE;
/*!40000 ALTER TABLE `valoracionmateria` DISABLE KEYS */;
INSERT INTO `valoracionmateria` VALUES (1,1,1,1,6),(2,1,1,2,7),(3,2,1,3,6),(4,3,1,4,6),(5,4,1,5,8),(6,5,1,6,4),(7,1,2,1,5),(8,1,2,2,7),(9,2,2,3,8),(10,3,2,4,5),(11,4,2,5,6),(12,5,2,6,4);
/*!40000 ALTER TABLE `valoracionmateria` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2019-04-09 10:05:53

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,97 @@
[
{
"parent_code": "0",
"label": "Andalucía",
"code": "01"
},
{
"parent_code": "0",
"label": "Aragón",
"code": "02"
},
{
"parent_code": "0",
"label": "Asturias, Principado de",
"code": "03"
},
{
"parent_code": "0",
"label": "Balears, Illes",
"code": "04"
},
{
"parent_code": "0",
"label": "Canarias",
"code": "05"
},
{
"parent_code": "0",
"label": "Cantabria",
"code": "06"
},
{
"parent_code": "0",
"label": "Castilla y León",
"code": "07"
},
{
"parent_code": "0",
"label": "Castilla - La Mancha",
"code": "08"
},
{
"parent_code": "0",
"label": "Cataluńa",
"code": "09"
},
{
"parent_code": "0",
"label": "Comunitat Valenciana",
"code": "10"
},
{
"parent_code": "0",
"label": "Extremadura",
"code": "11"
},
{
"parent_code": "0",
"label": "Galicia",
"code": "12"
},
{
"parent_code": "0",
"label": "Madrid, Comunidad de",
"code": "13"
},
{
"parent_code": "0",
"label": "Murcia, Región de",
"code": "14"
},
{
"parent_code": "0",
"label": "Navarra, Comunidad Foral de",
"code": "15"
},
{
"parent_code": "0",
"label": "País Vasco",
"code": "16"
},
{
"parent_code": "0",
"label": "Rioja, La",
"code": "17"
},
{
"parent_code": "0",
"label": "Ceuta",
"code": "18"
},
{
"parent_code": "0",
"label": "Melilla",
"code": "19"
}
]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,262 @@
[
{
"parent_code": "01",
"code": "04",
"label": "Almería"
},
{
"parent_code": "01",
"code": "11",
"label": "Cádiz"
},
{
"parent_code": "01",
"code": "14",
"label": "Córdoba"
},
{
"parent_code": "01",
"code": "18",
"label": "Granada"
},
{
"parent_code": "01",
"code": "21",
"label": "Huelva"
},
{
"parent_code": "01",
"code": "23",
"label": "Jaén"
},
{
"parent_code": "01",
"code": "29",
"label": "Málaga"
},
{
"parent_code": "01",
"code": "41",
"label": "Sevilla"
},
{
"parent_code": "02",
"code": "22",
"label": "Huesca"
},
{
"parent_code": "02",
"code": "44",
"label": "Teruel"
},
{
"parent_code": "02",
"code": "50",
"label": "Zaragoza"
},
{
"parent_code": "03",
"code": "33",
"label": "Asturias"
},
{
"parent_code": "04",
"code": "07",
"label": "Balears, Illes"
},
{
"parent_code": "05",
"code": "35",
"label": "Palmas, Las"
},
{
"parent_code": "05",
"code": "38",
"label": "Santa Cruz de Tenerife"
},
{
"parent_code": "06",
"code": "39",
"label": "Cantabria"
},
{
"parent_code": "07",
"code": "05",
"label": "Ávila"
},
{
"parent_code": "07",
"code": "09",
"label": "Burgos"
},
{
"parent_code": "07",
"code": "24",
"label": "León"
},
{
"parent_code": "07",
"code": "34",
"label": "Palencia"
},
{
"parent_code": "07",
"code": "37",
"label": "Salamanca"
},
{
"parent_code": "07",
"code": "40",
"label": "Segovia"
},
{
"parent_code": "07",
"code": "42",
"label": "Soria"
},
{
"parent_code": "07",
"code": "47",
"label": "Valladolid"
},
{
"parent_code": "07",
"code": "49",
"label": "Zamora"
},
{
"parent_code": "08",
"code": "02",
"label": "Albacete"
},
{
"parent_code": "08",
"code": "13",
"label": "Ciudad Real"
},
{
"parent_code": "08",
"code": "16",
"label": "Cuenca"
},
{
"parent_code": "08",
"code": "19",
"label": "Guadalajara"
},
{
"parent_code": "08",
"code": "45",
"label": "Toledo"
},
{
"parent_code": "09",
"code": "08",
"label": "Barcelona"
},
{
"parent_code": "09",
"code": "17",
"label": "Girona"
},
{
"parent_code": "09",
"code": "25",
"label": "Lleida"
},
{
"parent_code": "09",
"code": "43",
"label": "Tarragona"
},
{
"parent_code": "10",
"code": "03",
"label": "Alicante/Alacant"
},
{
"parent_code": "10",
"code": "12",
"label": "Castellón/Castelló"
},
{
"parent_code": "10",
"code": "46",
"label": "Valencia/València"
},
{
"parent_code": "11",
"code": "06",
"label": "Badajoz"
},
{
"parent_code": "11",
"code": "10",
"label": "Cáceres"
},
{
"parent_code": "12",
"code": "15",
"label": "Coruña, A"
},
{
"parent_code": "12",
"code": "27",
"label": "Lugo"
},
{
"parent_code": "12",
"code": "32",
"label": "Ourense"
},
{
"parent_code": "12",
"code": "36",
"label": "Pontevedra"
},
{
"parent_code": "13",
"code": "28",
"label": "Madrid"
},
{
"parent_code": "14",
"code": "30",
"label": "Murcia"
},
{
"parent_code": "15",
"code": "31",
"label": "Navarra"
},
{
"parent_code": "16",
"code": "01",
"label": "Araba/Álava"
},
{
"parent_code": "16",
"code": "48",
"label": "Bizkaia"
},
{
"parent_code": "16",
"code": "20",
"label": "Gipuzkoa"
},
{
"parent_code": "17",
"code": "26",
"label": "Rioja, La"
},
{
"parent_code": "18",
"code": "51",
"label": "Ceuta"
},
{
"parent_code": "19",
"code": "52",
"label": "Melilla"
}
]

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -114,6 +114,24 @@ public class Utils {
} }
/**
* Obtiene un número entero a través de un objeto Scanner
* @return Número entero introducido por el usuario.
*/
public static double obtenerDoublePorScanner() {
Scanner sc = new Scanner(System.in);
while (true) {
try {
return sc.nextDouble();
} catch (Exception ex) {
System.out.println("Error, introduce un número double: ");
sc.nextLine();
}
}
}
/** /**
* Obtiene un número entero a través de un JOptionPane * Obtiene un número entero a través de un JOptionPane
* @return Número entero introducido a través de un JOptionPane. * @return Número entero introducido a través de un JOptionPane.
@@ -143,6 +161,11 @@ public class Utils {
return num; return num;
} }
public static double obtenerDoubleConDescripcion(String desc) {
System.out.println(desc);
return obtenerDoublePorScanner();
}
/** /**
* *
* @return Número entero introducido por el usuario * @return Número entero introducido por el usuario

View File

@@ -0,0 +1,33 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mongoDB;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class Ej01_ConexionBasica_Ping {
public static void main(String[] args) {
try {
ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/");
MongoClient mongoClient = MongoClients.create(connectionString);
MongoDatabase database = mongoClient.getDatabase("ComunidadesProvinciasPoblaciones");
Bson command = new BsonDocument("ping", new BsonInt64(1));
database.runCommand(command);
System.out.println("Pinged your deployment. You successfully connected to MongoDB!");
} catch (MongoException me) {
System.err.println(me);
}
}
}

View File

@@ -0,0 +1,165 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mongoDB;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
public class Ej02_ObtencionElementos {
// Obtener todos los documentos de una colección.
private static void getAllDocuments(MongoCollection<Document> col) {
System.out.println("Obteniendo todos los elementos de la colección");
// Performing a read operation on the collection.
FindIterable<Document> fi = col.find();
MongoCursor<Document> cursor = fi.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
// Filtrar documentos dentro de una colección.
private static void getSelectiveDocument(MongoCollection<Document> col) {
System.out.println("Filtrando elementos de una colección");
// Performing a read operation on the collection.
FindIterable<Document> fi = col.find(Filters.eq("label", "Andalucía"));
MongoCursor<Document> cursor = fi.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
// Obtener documentos que no cumplan un criterio.
private static void getDocumentsWithNotInClause(MongoCollection<Document> col) {
System.out.println("Filtrando documentos con una claúsula 'not in'");
// Performing a read operation on the collection.
FindIterable<Document> fi = col.find(Filters.ne("label", "Andalucía"));
MongoCursor<Document> cursor = fi.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
/**
* Ejemplo de modificación de una entidad
* @param col
*/
private static void updateDocument (MongoCollection<Document> col) {
try {
Document query = new Document().append("code", "01");
Bson update = Updates.combine(Updates.set("label", "Andalucía 02"));
UpdateResult result = col.updateOne(query, update);
System.out.println("Modificados: " + result.getModifiedCount());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
* @param col
*/
private static void insertDocument (MongoCollection<Document> col) {
try {
Document doc = new Document().append("parent_code", "0")
.append("code", "20")
.append("label", "Gibraltar");
col.insertOne(doc);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
* @param col
*/
private static void deleteDocument (MongoCollection<Document> col) {
try {
Bson query = Filters.eq("code", "20");
DeleteResult result = col.deleteOne(query);
System.out.println("Eliminados: " + result.getDeletedCount());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
* @param args
*/
public static void main(String[] args) {
// Mongodb inicializando parámetros.
int port_no = 27017;
String host_name = "localhost", db_name = "ComunidadesProvinciasPoblaciones",
db_coll_name = "ccaa";
// Mongodb creando la cadena de conexión.
String client_url = "mongodb://" + host_name + ":" + port_no + "/" + db_name;
MongoClientURI uri = new MongoClientURI(client_url);
// Conectando y obteniendo un cliente.
MongoClient mongo_client = new MongoClient(uri);
// Obteniendo un enlace a la base de datos.
MongoDatabase db = mongo_client.getDatabase(db_name);
// Obteniendo la colección de la base de datos
MongoCollection<Document> coll = db.getCollection(db_coll_name);
// Obteniendo todos los documentos de la colección.
// getAllDocuments(coll); System.out.println("\n");
// Filtrando documentos mediante una claúsula "eq".
// getSelectiveDocument(coll); System.out.println("\n");
// Filtrando documentos con una claúsula "neq".
// getDocumentsWithNotInClause(coll); System.out.println();
// Modificación de una entidad
// updateDocument(coll);
// Inserción de una entidad
// insertDocument(coll);
// Eliminación de una entidad
// deleteDocument(coll);
}
}

View File

@@ -0,0 +1,47 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManagerV1 {
private static Connection conexion = null;
public static Connection getConexion () throws SQLException {
// Si es la primera vez que accedemos a la conexi<78>n, debemos instanciarla
if (conexion == null) {
conectar();
}
// Compruebo si la conexi<78>n sigue estando activa
while (!conexion.isValid(5)) {
conectar();
}
return conexion;
}
private static void conectar () throws SQLException {
String driver = JDBCPropiedades.getProperty("JDBC_DRIVER_CLASS");
String user = JDBCPropiedades.getProperty("JDBC_USER");
String password = JDBCPropiedades.getProperty("JDBC_PASSWORD");
String host = JDBCPropiedades.getProperty("JDBC_HOST");
String schema = JDBCPropiedades.getProperty("JDBC_SCHEMA_NAME");
String properties = JDBCPropiedades.getProperty("JDBC_PROPERTIES");
try {
Class.forName(driver);
conexion = (Connection) DriverManager.getConnection ("jdbc:mysql://" + host + "/" + schema + properties, user, password);
}
catch (ClassNotFoundException ex) {
System.out.println("Imposible acceder al driver Mysql");
}
}
}

View File

@@ -0,0 +1,117 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
public class Ejemplo01_ConexionBasica {
/**
*
*/
private static void pruebaConsultaBasica () {
try {
// A través de la siguiente línea comprobamos si tenemos acceso al driver MySQL, si no fuera así
// no podemos trabajar con esa BBDD.
Class.forName("com.mysql.cj.jdbc.Driver");
// Necesitamos obtener un acceso a la BBDD, eso se materializa en un objeto de tipo Connection, al cual
// le tenemos que pasar los parámetros de conexión.
Connection conexion = (Connection) DriverManager.getConnection (
"jdbc:mysql://localhost:3310/tutorialjavacoches?serverTimezone=UTC",
"root", "1234");
// Para poder ejecutar una consulta necesitamos utilizar un objeto de tipo Statement
Statement s = (Statement) conexion.createStatement();
// La ejecución de la consulta se realiza a través del objeto Statement y se recibe en forma de objeto
// de tipo ResultSet, que puede ser navegado para descubrir todos los registros obtenidos por la consulta
ResultSet rs = s.executeQuery ("select * from coche");
// Navegación del objeto ResultSet
while (rs.next()) {
System.out.println (rs.getInt("id") + " " + rs.getString (2)+
" " + rs.getString(3) + " " + rs.getString(4) +
" " + rs.getString(5));
}
// Cierre de los elementos
rs.close();
s.close();
conexion.close();
}
catch (ClassNotFoundException ex) {
System.out.println("Imposible acceder al driver Mysql");
ex.printStackTrace();
}
catch (SQLException ex) {
System.out.println("Error en la ejecución SQL: " + ex.getMessage());
ex.printStackTrace();
}
}
/**
*
*/
private static void pruebaConsultaPorFicheroDePropiedades () {
String driver = JDBCPropiedades.getProperty("JDBC_DRIVER_CLASS");
String user = JDBCPropiedades.getProperty("JDBC_USER");
String password = JDBCPropiedades.getProperty("JDBC_PASSWORD");
String host = JDBCPropiedades.getProperty("JDBC_HOST");
String schema = JDBCPropiedades.getProperty("JDBC_SCHEMA_NAME");
String properties = JDBCPropiedades.getProperty("JDBC_PROPERTIES");
try {
// A través de la siguiente línea comprobamos si tenemos acceso al driver MySQL, si no fuera así
// no podemos trabajar con esa BBDD.
Class.forName(driver);
// Necesitamos obtener un acceso a la BBDD, eso se materializa en un objeto de tipo Connection, al cual
// le tenemos que pasar los parámetros de conexión.
Connection conexion = (Connection) DriverManager.getConnection (
"jdbc:mysql://" + host + "/" + schema + properties,
user, password);
// Para poder ejecutar una consulta necesitamos utilizar un objeto de tipo Statement
Statement s = (Statement) conexion.createStatement();
// La ejecución de la consulta se realiza a través del objeto Statement y se recibe en forma de objeto
// de tipo ResultSet, que puede ser navegado para descubrir todos los registros obtenidos por la consulta
ResultSet rs = s.executeQuery ("select * from coche");
// Navegaci<63>n del objeto ResultSet
while (rs.next()) {
System.out.println (rs.getInt (1) + " " + rs.getString (2)+ " " + rs.getString(3));
}
// Cierre de los elementos
rs.close();
s.close();
conexion.close();
}
catch (ClassNotFoundException ex) {
System.out.println("Imposible acceder al driver Mysql");
}
catch (SQLException ex) {
System.out.println("Error en la ejecución SQL: " + ex.getMessage());
}
}
/**
*
* @param args
*/
public static void main(String[] args) {
pruebaConsultaBasica();
// pruebaConsultaPorFicheroDePropiedades();
}
}

View File

@@ -0,0 +1,136 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
public class Ejemplo02_EjemplosInsertUpdateyDelete {
/**
*
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
private static Connection getConexion()
throws ClassNotFoundException, SQLException {
String driver = JDBCPropiedades.getProperty("JDBC_DRIVER_CLASS");
String user = JDBCPropiedades.getProperty("JDBC_USER");
String password = JDBCPropiedades.getProperty("JDBC_PASSWORD");
String host = JDBCPropiedades.getProperty("JDBC_HOST");
String schema = JDBCPropiedades.getProperty("JDBC_SCHEMA_NAME");
String properties = JDBCPropiedades.getProperty("JDBC_PROPERTIES");
Class.forName(driver);
return (Connection) DriverManager.getConnection ("jdbc:mysql://" + host + "/" + schema + properties, user, password);
}
/**
*
* @return
* @throws SQLException
*/
private static int getSiguienteIdValidoConcesionario(Connection conn) throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select max(id) as maximoId "
+ "from tutorialjavacoches.concesionario");
if (rs.next()) {
return rs.getInt(1) + 1;
}
return 1;
}
/**
* @throws SQLException
*
*/
private static void realizaInsert (Connection conn) throws SQLException {
Statement s = (Statement) conn.createStatement();
int filasAfectadas = s.executeUpdate(
"insert into tutorialjavacoches.concesionario "
+ "(id, cif, nombre, localidad) values ("
+ getSiguienteIdValidoConcesionario(conn)
+ ", '111111A', 'Concesionario nuevo', 'Rute')");
System.out.println("Filas afectadas: " + filasAfectadas);
s.close();
}
/**
* @throws SQLException
*
*/
private static void realizaUpdate (Connection conn, String nombreMod,
String localidadMod, int id) throws SQLException {
Statement s = (Statement) conn.createStatement();
int filasAfectadas = s.executeUpdate("update tutorialjavacoches.concesionario "
+ "set nombre = '" + nombreMod + "', "
+ "localidad = '" + localidadMod + "'\r\n"
+ "where id = " + id);
System.out.println("Filas afectadas: " + filasAfectadas);
s.close();
}
/**
* @throws SQLException
*
*/
private static void realizaDelete (Connection conn, int id) throws SQLException {
Statement s = (Statement) conn.createStatement();
int filasAfectadas = s.executeUpdate("Delete from "
+ "tutorialjavacoches.concesionario "
+ "where id = " + id);
System.out.println("Filas afectadas: " + filasAfectadas);
s.close();
}
/**
*
* @param args
*/
public static void main(String[] args) {
try {
Connection conn = getConexion();
// realizaInsert(conn);
realizaUpdate(conn, "Concesionario José María", "Lucena", 21);
// realizaDelete(conn, 22);
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,153 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Ejemplo03_EjemplosInsertUpdateyDeleteConPreparedStatement {
/**
*
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
private static Connection getConexion() throws ClassNotFoundException, SQLException {
String driver = JDBCPropiedades.getProperty("JDBC_DRIVER_CLASS");
String user = JDBCPropiedades.getProperty("JDBC_USER");
String password = JDBCPropiedades.getProperty("JDBC_PASSWORD");
String host = JDBCPropiedades.getProperty("JDBC_HOST");
String schema = JDBCPropiedades.getProperty("JDBC_SCHEMA_NAME");
String properties = JDBCPropiedades.getProperty("JDBC_PROPERTIES");
Class.forName(driver);
return (Connection) DriverManager.getConnection ("jdbc:mysql://" + host + "/" + schema + properties, user, password);
}
/**
*
* @return
* @throws SQLException
*/
private static int getSiguienteIdValidoConcesionario(Connection conn) throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select max(id) as maximoId "
+ "from tutorialjavacoches.concesionario");
if (rs.next()) {
return rs.getInt(1) + 1;
}
return 1;
}
/**
* @throws SQLException
*
*/
private static void realizaInsert (Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(
"insert into tutorialjavacoches.concesionario "
+ "(id, cif, nombre, localidad) "
+ "values (?, ?, ?, ?)");
ps.setInt(1, getSiguienteIdValidoConcesionario(conn));
ps.setString(2, "111111B");
ps.setString(3, "Hermanos O'Bryan");
ps.setString(4, "Lucena");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
java.util.Date fechaNac = null;
try {
fechaNac = sdf.parse("19/03/1977 15:33:00");
} catch (ParseException e) {
e.printStackTrace();
}
ps.setDate(0, new java.sql.Date(fechaNac.getTime()) );
int filasAfectadas = ps.executeUpdate();
System.out.println("Filas afectadas: " + filasAfectadas);
ps.close();
}
/**
* @throws SQLException
*
*/
private static void realizaUpdate (Connection conn, String nombreMod,
String localidadMod, int idMod) throws SQLException {
Statement s = (Statement) conn.createStatement();
int filasAfectadas = s.executeUpdate("update tutorialjavacoches.concesionario "
+ "set nombre = '" + nombreMod + "', "
+ "localidad = '" + localidadMod + "'\r\n"
+ "where id = " + idMod);
System.out.println("Filas afectadas: " + filasAfectadas);
s.close();
}
/**
* @throws SQLException
*
*/
private static void realizaDelete (Connection conn, int idMod) throws SQLException {
Statement s = (Statement) conn.createStatement();
int filasAfectadas = s.executeUpdate("Delete from "
+ "tutorialjavacoches.concesionario "
+ "where id = " + idMod);
System.out.println("Filas afectadas: " + filasAfectadas);
s.close();
}
/**
*
* @param args
*/
public static void main(String[] args) {
try {
Connection conn = getConexion();
realizaInsert(conn);
// realizaUpdate(conn, "Concesionario José María", "Lucena", 22);
// realizaDelete(conn, 23);
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,91 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Ejemplo04_ResultSetMetadata {
/**
*
* @param conn
* @param tabla
* @throws SQLException
*/
private static void consultarTabla (Connection conn, String tabla)
throws SQLException{
Statement s = (Statement) conn.createStatement();
ResultSet rs = s.executeQuery ("select * from " + tabla);
// A través del objeto ResultSetMetaData obtenemos información sobre las características de los campos que
// posee el conjunto de registros que hemos obtenido con la consulta. Gracias a eso podemos hacer una visualización
// enriquecida del contenido del objeto ResultSet
ResultSetMetaData rsmd= rs.getMetaData();
// Impresión en pantalla de los tipos de las columnas que forman el resultado del ResultSet
System.out.println("\n-------------------------------------------------------------");
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnTypeName(i) + "\t");
}
System.out.println("\n-------------------------------------------------------------");
// Impresión en pantalla de las etiquetas de nombre de las columnas del objeto ResultSet
System.out.println("\n-------------------------------------------------------------");
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnLabel(i) + "\t");
}
System.out.println("\n-------------------------------------------------------------");
// Recorrido del ResultSet, diferenciando entre los tipos de datos que pueden tener las columnas
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
if (rsmd.getColumnTypeName(i).equalsIgnoreCase("INT")) {
System.out.print(rs.getInt(rsmd.getColumnLabel(i)) + "\t");
}
if (rsmd.getColumnTypeName(i).equalsIgnoreCase("VARCHAR")) {
System.out.print(rs.getString(rsmd.getColumnLabel(i)) + "\t");
}
if (rsmd.getColumnTypeName(i).equalsIgnoreCase("DATETIME")) {
System.out.print(rs.getDate(rsmd.getColumnLabel(i)) + "\t");
}
if (rsmd.getColumnTypeName(i).equalsIgnoreCase("TINYINT")) {
System.out.print(rs.getBoolean(rsmd.getColumnLabel(i)) + "\t");
}
if (rsmd.getColumnTypeName(i).equalsIgnoreCase("FLOAT")) {
System.out.print(rs.getFloat(rsmd.getColumnLabel(i)) + "\t");
}
}
System.out.println("\n");
}
rs.close();
s.close();
}
/**
*
* @param args
*/
public static void main(String[] args) {
try {
Connection conn = ConnectionManagerV1.getConexion();
consultarTabla (conn, "coche");
}
catch (SQLException ex) {
System.out.println("Error en la ejecución SQL: " + ex.getMessage());
}
}
}

View File

@@ -0,0 +1,260 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import tutorialJava.modelosBasesDeDatosComunesJPA.ventaDeCoches.Coche;
import tutorialJava.modelosBasesDeDatosComunesJPA.ventaDeCoches.Fabricante;
import tutorialJava.modelosBasesDeDatosComunesJPA.ventaDeCoches.Venta;
public class Ejemplo05_JPA_conexionBasica {
/**
*
*/
private static void obtencionUnaSolaEntidad () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
Coche coche = (Coche) em.find(Coche.class, 1);
System.out.println("Coche localizado -> " + coche.getId() + " " + coche.getModelo() + " " +
coche.getColor());
em.close();
}
/**
*
*/
private static void obtencionUnaSolaEntidadSegundoMetodo () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
Query q = em.createNativeQuery("SELECT * FROM coche where id = ?", Coche.class);
q.setParameter(1, 100);
Coche coche = (Coche) q.getSingleResult();
if (coche != null) {
System.out.println("Coche localizado -> " + coche.getId() + " " + coche.getModelo() + " " +
coche.getColor());
}
em.close();
}
/**
*
*/
private static void obtencionUnaSolaEntidadTercerMetodo () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
TypedQuery<Coche> q = em.createQuery("SELECT c FROM Coche c where c.id = :id", Coche.class);
q.setParameter("id", 100);
Coche coche = (Coche) q.getSingleResult();
if (coche != null) {
System.out.println("Coche localizado -> " + coche.getId() + " " + coche.getModelo() + " " +
coche.getColor());
}
em.close();
}
/**
*
*/
private static void listadoEntidades () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
Query q = em.createNativeQuery("SELECT * FROM coche;", Coche.class);
List<Coche> coches = (List<Coche>) q.getResultList();
for (Coche coche : coches) {
System.out.println("Coche: " + coche.getId() + " modelo: " + coche.getModelo());
}
em.close();
}
/**
*
*/
private static void listadoEntidadesSegundoMetodo () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
TypedQuery<Coche> q = em.createQuery("SELECT c FROM Coche c", Coche.class);
List<Coche> coches = (List<Coche>) q.getResultList();
for (Coche coche : coches) {
System.out.println("Coche: " + coche.getId() + " modelo: " + coche.getModelo());
}
em.close();
}
/**
*
*/
private static void listadoEntidadesTercerMetodo () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
Query q = em.createNamedQuery("Coche.findAll");//("SELECT c FROM Coche c", Coche.class);
List<Coche> coches = (List<Coche>) q.getResultList();
for (Coche coche : coches) {
System.out.println("Coche: " + coche.getId() + " modelo: " + coche.getModelo());
}
em.close();
}
/**
*
*/
private static void obtencionEntidadesRelacionadas () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
Coche coche = (Coche) em.find(Coche.class, 1);
System.out.println("Fabricante -> " + coche.getFabricante().getId() + " " + coche.getFabricante().getNombre());
for (Venta venta : coche.getVentas()) {
System.out.println("Venta -> " + venta.getId() + " " + venta.getPrecioVenta() + " " +
venta.getFecha());
}
em.close();
}
/**
*
*/
private static void creacionEntidad () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
Fabricante fab = new Fabricante();
fab.setCif("12345678A");
fab.setNombre("Coches Rafa");
em.getTransaction().begin();
em.persist(fab);
em.getTransaction().commit();
TypedQuery<Fabricante> q = em.createQuery("SELECT f FROM Fabricante as f", Fabricante.class);
List<Fabricante> fabricantes = q.getResultList();
for (Fabricante fabEnLista : fabricantes) {
System.out.println("Fabricante: " + fabEnLista.getId() + " CIF: " + fabEnLista.getCif() + " Nombre: " + fabEnLista.getNombre());
}
em.close();
}
/**
*
*/
private static void modificacionEntidad () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
TypedQuery<Fabricante> q = em.createQuery("SELECT f FROM Fabricante as f where f.cif = '12345678A'", Fabricante.class);
List<Fabricante> fabricantes = q.getResultList();
em.getTransaction().begin();
for (Fabricante fabEnLista : fabricantes) {
fabEnLista.setNombre("Modificado");
em.persist(fabEnLista);
}
em.getTransaction().commit();
em.close();
}
/**
*
*/
private static void eliminacionEntidad () {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("VentaDeCoches");
EntityManager em = entityManagerFactory.createEntityManager();
TypedQuery<Fabricante> q = em.createQuery("SELECT f FROM Fabricante as f where f.cif = '12345678A'", Fabricante.class);
List<Fabricante> fabricantes = q.getResultList();
em.getTransaction().begin();
for (Fabricante fabEnLista : fabricantes) {
em.remove(fabEnLista);
}
em.getTransaction().commit();
em.close();
}
/**
*
* @param args
*/
public static void main(String[] args) {
obtencionUnaSolaEntidad();
//obtencionUnaSolaEntidadSegundoMetodo();
//obtencionUnaSolaEntidadTercerMetodo();
//listadoEntidades();
//listadoEntidadesSegundoMetodo();
//listadoEntidadesTercerMetodo();
//obtencionEntidadesRelacionadas();
//creacionEntidad();
//modificacionEntidad();
//eliminacionEntidad();
}
}

View File

@@ -0,0 +1,10 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
public class ImposibleConectarException extends Exception {
public ImposibleConectarException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,69 @@
package tutorialJava.capitulo8_Acceso_A_Datos.mysql;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class JDBCPropiedades {
private static Properties propiedades = null;
public JDBCPropiedades () {
super();
}
/**
*
* @return
*/
private static Properties getPropiedades() {
if (propiedades == null) {
propiedades = new Properties();
try {
File file = new File("./src/tutorialJava/capitulo8_Acceso_A_Datos/mysql/jdbc.properties");
propiedades.load(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return propiedades;
}
/**
*
* @param nombrePropiedad
* @return
*/
public static String getProperty(String nombrePropiedad) {
return getPropiedades().getProperty(nombrePropiedad);
}
/**
*
* @param nombrePropiedad
* @return
*/
public static int getIntProperty (String nombrePropiedad) {
return Integer.parseInt(getPropiedades().getProperty(nombrePropiedad));
}
/**
*
* @param nombrePropiedad
* @return
*/
public static Float getFloatProperty (String nombrePropiedad) {
return Float.parseFloat(getPropiedades().getProperty(nombrePropiedad));
}
}

View File

@@ -0,0 +1,7 @@
# parámetros de conexión a BBDD
JDBC_DRIVER_CLASS=com.mysql.cj.jdbc.Driver
JDBC_USER=root
JDBC_PASSWORD=1234
JDBC_HOST=localhost:3310
JDBC_SCHEMA_NAME=tutorialjavacoches
JDBC_PROPERTIES=?autoReconnect=true&serverTimezone=Europe/Madrid&useSSL=False&allowPublicKeyRetrieval=TRUE

View File

@@ -0,0 +1,49 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo01_GestionGraficaFabricante;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private static Connection conexion = null;
public static Connection getConexion () throws SQLException {
// Si es la primera vez que accedemos a la conexión, debemos instanciarla
if (conexion == null) {
conectar();
}
// Compruebo si la conexión sigue estando activa
while (!conexion.isValid(5)) {
conectar();
}
return conexion;
}
/**
*
* @throws SQLException
*/
private static void conectar () throws SQLException {
try {
// A través de la siguiente línea comprobamos si tenemos acceso al driver MySQL, si no fuera así
// no podemos trabajar con esa BBDD.
Class.forName("com.mysql.cj.jdbc.Driver");
// Necesitamos obtener un acceso a la BBDD, eso se materializa en un objeto de tipo Connection, al cual
// le tenemos que pasar los parámetros de conexión.
conexion = (Connection) DriverManager.getConnection (
"jdbc:mysql://localhost:3310/tutorialjavacoches?serverTimezone=UTC",
"root",
"1234");
}
catch (ClassNotFoundException ex) {
System.out.println("Imposible acceder al driver Mysql");
}
}
}

View File

@@ -0,0 +1,50 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo01_GestionGraficaFabricante;
public class Fabricante {
private int id;
private String cif;
private String nombre;
/**
*
*/
public Fabricante() {
super();
}
/**
*
* @param id
* @param cif
* @param nombre
*/
public Fabricante(int id, String cif, String nombre) {
super();
this.id = id;
this.cif = cif;
this.nombre = nombre;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCif() {
return cif;
}
public void setCif(String cif) {
this.cif = cif;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}

View File

@@ -0,0 +1,124 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo01_GestionGraficaFabricante;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GestionFabricante extends SupertipoGestion {
public static Fabricante getPrimero(Connection conn) throws SQLException {
return getFabricante (conn,
"select * from tutorialjavacoches.fabricante "
+ "order by id asc limit 1");
}
public static Fabricante getUltimo(Connection conn) throws SQLException {
return getFabricante(conn,
"select * from tutorialjavacoches.fabricante "
+ "order by id desc limit 1");
}
public static Fabricante getAnterior(Connection conn, int idActual) throws SQLException {
String sql = "select * from tutorialjavacoches.fabricante where id < " + idActual
+ " order by id desc limit 1";
// System.out.println("sql: " + sql);
return getFabricante (conn, sql);
}
public static Fabricante getSiguiente(Connection conn, int idActual) throws SQLException {
return getFabricante (conn,
"select * from tutorialjavacoches.fabricante where id > " + idActual
+ " order by id asc limit 1");
}
private static Fabricante getFabricante(Connection conn, String sql) throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(sql);
Fabricante f = null;
if (rs.next()) {
f = new Fabricante();
f.setId(rs.getInt("id"));
f.setCif(rs.getString("cif"));
f.setNombre(rs.getString("nombre"));
}
return f;
}
/**
*
*/
public static int insercion (Fabricante f, Connection conn) {
try {
int nuevoId = nextIdEnTabla("fabricante");
PreparedStatement ps = conn.prepareStatement(""
+ "insert into fabricante (id, cif, nombre) "
+ "values (?, ?, ?)");
ps.setInt(1, nuevoId);
ps.setString(2, f.getCif());
ps.setString(3, f.getNombre());
ps.executeUpdate();
return nuevoId;
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
/**
*
*/
public static void modificacion (Fabricante f, Connection conn) {
try {
PreparedStatement ps = conn.prepareStatement(""
+ "update fabricante set cif = ?, nombre = ? "
+ "where id = ?");
ps.setString(1, f.getCif());
ps.setString(2, f.getNombre());
ps.setInt(3, f.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
*/
public static void eliminacion (int id, Connection conn) {
try {
PreparedStatement ps = conn.prepareStatement(""
+ "delete fabricante where id = ?");
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,30 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo01_GestionGraficaFabricante;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SupertipoGestion {
/**
*
* @param nombreTabla
* @return
*/
protected static int nextIdEnTabla(String nombreTabla) {
try {
Statement s = ConnectionManager.getConexion().createStatement();
ResultSet rs = s.executeQuery("Select max(id) from " + nombreTabla);
if (rs.next()) {
return rs.getInt(1) + 1;
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
}

View File

@@ -0,0 +1,381 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo01_GestionGraficaFabricante;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.GridBagConstraints;
import java.awt.Font;
import java.awt.Insets;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.awt.event.ActionEvent;
public class VentanaFabricante extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField jtfId;
private JTextField jtfCif;
private JTextField jtfNombre;
private JPanel panel;
private JButton btnPrimero;
private JButton btnAnterior;
private JButton btnSiguiente;
private JButton btnUltimo;
private JButton btnNuevo;
private JButton btnGuardar;
private JButton btnEliminar;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VentanaFabricante frame = new VentanaFabricante();
frame.setVisible(true);
frame.cargarPrimero();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public VentanaFabricante() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblNewLabel = new JLabel("Gestión de fabricantes");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 17));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.gridwidth = 2;
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
contentPane.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Id:");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 1;
contentPane.add(lblNewLabel_1, gbc_lblNewLabel_1);
jtfId = new JTextField();
jtfId.setEnabled(false);
GridBagConstraints gbc_jtfId = new GridBagConstraints();
gbc_jtfId.insets = new Insets(0, 0, 5, 0);
gbc_jtfId.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfId.gridx = 1;
gbc_jtfId.gridy = 1;
contentPane.add(jtfId, gbc_jtfId);
jtfId.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("CIF:");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_2.gridx = 0;
gbc_lblNewLabel_2.gridy = 2;
contentPane.add(lblNewLabel_2, gbc_lblNewLabel_2);
jtfCif = new JTextField();
GridBagConstraints gbc_jtfCif = new GridBagConstraints();
gbc_jtfCif.insets = new Insets(0, 0, 5, 0);
gbc_jtfCif.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfCif.gridx = 1;
gbc_jtfCif.gridy = 2;
contentPane.add(jtfCif, gbc_jtfCif);
jtfCif.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("Nombre:");
GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
gbc_lblNewLabel_3.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_3.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_3.gridx = 0;
gbc_lblNewLabel_3.gridy = 3;
contentPane.add(lblNewLabel_3, gbc_lblNewLabel_3);
jtfNombre = new JTextField();
GridBagConstraints gbc_jtfNombre = new GridBagConstraints();
gbc_jtfNombre.insets = new Insets(0, 0, 5, 0);
gbc_jtfNombre.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfNombre.gridx = 1;
gbc_jtfNombre.gridy = 3;
contentPane.add(jtfNombre, gbc_jtfNombre);
jtfNombre.setColumns(10);
panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.gridwidth = 2;
gbc_panel.insets = new Insets(0, 0, 0, 5);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 0;
gbc_panel.gridy = 4;
contentPane.add(panel, gbc_panel);
btnPrimero = new JButton("");
btnPrimero.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cargarPrimero();
}
});
btnPrimero.setIcon(new ImageIcon(VentanaFabricante.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/gotostart.png")));
panel.add(btnPrimero);
btnAnterior = new JButton("");
btnAnterior.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cargarAnterior();
}
});
btnAnterior.setIcon(new ImageIcon(VentanaFabricante.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/previous.png")));
panel.add(btnAnterior);
btnSiguiente = new JButton("");
btnSiguiente.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cargarSiguiente();
}
});
btnSiguiente.setIcon(new ImageIcon(VentanaFabricante.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/next.png")));
panel.add(btnSiguiente);
btnUltimo = new JButton("");
btnUltimo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cargarUltimo();
}
});
btnUltimo.setIcon(new ImageIcon(VentanaFabricante.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/gotoend.png")));
panel.add(btnUltimo);
btnNuevo = new JButton("");
btnNuevo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nuevo();
}
});
btnNuevo.setIcon(new ImageIcon(VentanaFabricante.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/nuevo.png")));
panel.add(btnNuevo);
btnGuardar = new JButton("");
btnGuardar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
guardar();
}
});
btnGuardar.setIcon(new ImageIcon(VentanaFabricante.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/guardar.png")));
panel.add(btnGuardar);
btnEliminar = new JButton("");
btnEliminar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
eliminar();
}
});
btnEliminar.setIcon(new ImageIcon(VentanaFabricante.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/eliminar.png")));
panel.add(btnEliminar);
}
/**
*
*/
private void cargarPrimero () {
try {
Connection conn = ConnectionManager.getConexion();
Fabricante f = GestionFabricante.getPrimero(conn);
cargaFabricanteEnPantalla(f);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
*/
private void cargarAnterior () {
try {
String strIdActual = jtfId.getText();
if (!strIdActual.trim().equals("")) {
int idActual = Integer.parseInt(strIdActual);
Connection conn = ConnectionManager.getConexion();
Fabricante f = GestionFabricante.getAnterior(conn, idActual);
cargaFabricanteEnPantalla(f);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
*/
private void cargarUltimo () {
try {
Connection conn = ConnectionManager.getConexion();
Fabricante f = GestionFabricante.getUltimo(conn);
cargaFabricanteEnPantalla(f);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
*/
private void cargarSiguiente () {
try {
String strIdActual = jtfId.getText();
if (!strIdActual.trim().equals("")) {
int idActual = Integer.parseInt(strIdActual);
Connection conn = ConnectionManager.getConexion();
Fabricante f = GestionFabricante.getSiguiente(conn, idActual);
cargaFabricanteEnPantalla(f);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
* @param f
*/
private void cargaFabricanteEnPantalla(Fabricante f) {
if (f != null) {
jtfId.setText("" + f.getId());
jtfCif.setText(f.getCif());
jtfNombre.setText(f.getNombre());
}
}
/**
*
*/
private void nuevo() {
this.jtfId.setText("");
this.jtfCif.setText("");
this.jtfNombre.setText("");
}
/**
*
*/
private void guardar() {
try {
Fabricante f = new Fabricante();
f.setId(-1);
if (!this.jtfId.getText().trim().equals("")) { // El id tiene número
f.setId(Integer.parseInt(this.jtfId.getText()));
}
f.setCif(this.jtfCif.getText());
f.setNombre(this.jtfNombre.getText());
// Decido si debo insertar o modificar
Connection conn = ConnectionManager.getConexion();
if (f.getId() == -1) { // Inserción
int nuevoId = GestionFabricante.insercion(f, conn);
this.jtfId.setText("" + nuevoId);
}
else {
GestionFabricante.modificacion(f, conn);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
*/
private void eliminar () {
try {
String respuestas[] = new String[] {"", "No"};
int opcionElegida = JOptionPane.showOptionDialog(
null,
"¿Realmente desea eliminar el registro?",
"Eliminación de fabricante",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, respuestas,
respuestas[1]);
if(opcionElegida == 0) {
if (!this.jtfId.getText().trim().equals("")) {
int idActual = Integer.parseInt(this.jtfId.getText());
Connection conn = ConnectionManager.getConexion();
GestionFabricante.eliminacion(idActual, conn);
// Decido qué registro voy a mostrar en pantalla.
// Voy a comprobar si existe un anterior, si existe lo muestro
// Si no existe anterior compruebo si existe siguiente,
// si existe lo muestro. En caso contrario, no quedan registros
// así que muestro en blanco la pantalla
Fabricante fabriAMostrar = GestionFabricante.getAnterior(conn, idActual);
if (fabriAMostrar != null) { // Existe un anterior, lo muestro
cargaFabricanteEnPantalla(fabriAMostrar);
}
else {
fabriAMostrar = GestionFabricante.getSiguiente(conn, idActual);
if (fabriAMostrar != null) { // Existe un siguiente
cargaFabricanteEnPantalla(fabriAMostrar);
}
else { // No quedan registros en la tabla
nuevo();
}
}
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@@ -0,0 +1,44 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista.PanelCurso;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista.PanelEstudiante;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista.PanelMateria;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista.PanelValoracionMateriaOpcion1;
import tutorialJava.capitulo9_AWT_SWING.utils.Apariencia;
public class Principal extends JFrame {
// Establecer la apariencia típica de Windows
static {
Apariencia.setAparienciasOrdenadas(Apariencia.aparienciasOrdenadas);
}
public Principal() {
super("Gestión de centro educativo");
this.setBounds(0, 0, 800, 600);
PanelCurso panelCurso = new PanelCurso();
PanelMateria panelMateria = new PanelMateria();
JTabbedPane panelTabbed = new JTabbedPane();
panelTabbed.addTab("Cursos", panelCurso);
panelTabbed.addTab("Materias", panelMateria);
panelTabbed.addTab("Estudiantes", new PanelEstudiante());
panelTabbed.addTab("Valoración Materia", new PanelValoracionMateriaOpcion1());
panelTabbed.setSelectedIndex(0);
this.getContentPane().add(panelTabbed);
}
public static void main(String[] args) {
Principal ventana = new Principal();
ventana.setVisible(true);
}
}

View File

@@ -0,0 +1,49 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private static Connection conexion = null;
public static Connection getConexion () throws SQLException {
// Si es la primera vez que accedemos a la conexión, debemos instanciarla
if (conexion == null) {
conectar();
}
// Compruebo si la conexión sigue estando activa
while (!conexion.isValid(5)) {
conectar();
}
return conexion;
}
/**
*
* @throws SQLException
*/
private static void conectar () throws SQLException {
try {
// A través de la siguiente línea comprobamos si tenemos acceso al driver MySQL, si no fuera así
// no podemos trabajar con esa BBDD.
Class.forName("com.mysql.cj.jdbc.Driver");
// Necesitamos obtener un acceso a la BBDD, eso se materializa en un objeto de tipo Connection, al cual
// le tenemos que pasar los parámetros de conexión.
conexion = (Connection) DriverManager.getConnection (
"jdbc:mysql://localhost:3310/centroeducativo?serverTimezone=UTC",
"root",
"1234");
}
catch (ClassNotFoundException ex) {
System.out.println("Imposible acceder al driver Mysql");
}
}
}

View File

@@ -0,0 +1,106 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Curso;
public class ControladorCurso {
private static String nombreTabla = "centroeducativo.curso";
public static List<Curso> getTodos() {
List<Curso> l = new ArrayList<Curso>();
try {
ResultSet rs = ConnectionManager.getConexion().createStatement()
.executeQuery("Select * from " + nombreTabla);
while (rs.next()) {
Curso o = getEntidadFromResultSet(rs);
l.add(o);
}
} catch (SQLException e) {
e.printStackTrace();
}
return l;
}
public static Curso getPrimero() {
try {
return getEntidad (ConnectionManager.getConexion(),
"select * from " + nombreTabla
+ " order by id asc limit 1");
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Curso getUltimo() {
try {
return getEntidad(ConnectionManager.getConexion(),
"select * from " + nombreTabla
+ " order by id desc limit 1");
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Curso getAnterior(int idActual) {
try {
String sql = "select * from " + nombreTabla + " where id < " + idActual
+ " order by id desc limit 1";
return getEntidad (ConnectionManager.getConexion(), sql);
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Curso getSiguiente(int idActual) {
try {
return getEntidad (ConnectionManager.getConexion(),
"select * from " + nombreTabla + " where id > " + idActual
+ " order by id asc limit 1");
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private static Curso getEntidad(Connection conn, String sql) throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(sql);
Curso o = null;
if (rs.next()) {
o = getEntidadFromResultSet(rs);
}
return o;
}
private static Curso getEntidadFromResultSet (ResultSet rs) throws SQLException {
Curso o = new Curso();
o.setId(rs.getInt("id"));
o.setDescripcion(rs.getString("descripcion"));
return o;
}
}

View File

@@ -0,0 +1,44 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Estudiante;
public class ControladorEstudiante {
private static String nombreTabla = "estudiante";
public static List<Estudiante> getTodos() {
List<Estudiante> l = new ArrayList<Estudiante>();
try {
ResultSet rs = ConnectionManager.getConexion().createStatement()
.executeQuery("Select * from " + nombreTabla);
while (rs.next()) {
Estudiante o = getEntidadFromResultSet(rs);
l.add(o);
}
} catch (SQLException e) {
e.printStackTrace();
}
return l;
}
private static Estudiante getEntidadFromResultSet (ResultSet rs) throws SQLException {
Estudiante o = new Estudiante();
o.setId(rs.getInt("id"));
o.setNombre(rs.getString("nombre"));
return o;
}
}

View File

@@ -0,0 +1,113 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Curso;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Materia;
public class ControladorMateria {
private static String nombreTabla = "centroeducativo.materia";
public static Materia getPrimero() {
try {
return getEntidad (ConnectionManager.getConexion(),
"select * from " + nombreTabla
+ " order by id asc limit 1");
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Materia getUltimo() {
try {
return getEntidad(ConnectionManager.getConexion(),
"select * from " + nombreTabla
+ " order by id desc limit 1");
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Materia getAnterior(int idActual) {
try {
String sql = "select * from " + nombreTabla + " where id < " + idActual
+ " order by id desc limit 1";
return getEntidad (ConnectionManager.getConexion(), sql);
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Materia getSiguiente(int idActual) {
try {
return getEntidad (ConnectionManager.getConexion(),
"select * from " + nombreTabla + " where id > " + idActual
+ " order by id asc limit 1");
}
catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static List<Materia> getTodos() {
List<Materia> l = new ArrayList<Materia>();
try {
ResultSet rs = ConnectionManager.getConexion().createStatement()
.executeQuery("Select * from " + nombreTabla);
while (rs.next()) {
Materia o = getEntidadFromResultSet(rs);
l.add(o);
}
} catch (SQLException e) {
e.printStackTrace();
}
return l;
}
private static Materia getEntidadFromResultSet (ResultSet rs) throws SQLException {
Materia o = new Materia();
o.setId(rs.getInt("id"));
o.setCursoId(rs.getInt("curso_id"));
o.setAcronimo(rs.getString("acronimo"));
o.setNombre(rs.getString("nombre"));
return o;
}
private static Materia getEntidad(Connection conn, String sql) throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(sql);
Materia o = null;
if (rs.next()) {
o = new Materia();
o.setId(rs.getInt("id"));
o.setCursoId(rs.getInt("curso_id"));
o.setAcronimo(rs.getString("acronimo"));
o.setNombre(rs.getString("nombre"));
}
return o;
}
}

View File

@@ -0,0 +1,45 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Curso;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Materia;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Profesor;
public class ControladorProfesor {
private static String nombreTabla = "profesor";
public static List<Profesor> getTodos() {
List<Profesor> l = new ArrayList<Profesor>();
try {
ResultSet rs = ConnectionManager.getConexion().createStatement()
.executeQuery("Select * from " + nombreTabla);
while (rs.next()) {
Profesor o = getEntidadFromResultSet(rs);
l.add(o);
}
} catch (SQLException e) {
e.printStackTrace();
}
return l;
}
private static Profesor getEntidadFromResultSet (ResultSet rs) throws SQLException {
Profesor o = new Profesor();
o.setId(rs.getInt("id"));
o.setNombre(rs.getString("nombre"));
return o;
}
}

View File

@@ -0,0 +1,73 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Curso;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.ValoracionMateria;
public class ControladorValoracionMateria {
private static String nombreTabla = "valoracionmateria";
public static ValoracionMateria findByIdMateriaAndIdProfesorAndIdEstudiante(
int idMateria, int idProfesor, int idEstudiante) {
ValoracionMateria v = null;
try {
PreparedStatement ps = ConnectionManager.getConexion().prepareStatement(
"select * from " + nombreTabla + " where idProfesor = ? and"
+ " idMateria = ? and idEstudiante = ? limit 1 ");
ps.setInt(1, idProfesor);
ps.setInt(2, idMateria);
ps.setInt(3, idEstudiante);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
v = getEntidadFromResultSet(rs);
}
} catch (SQLException e) {
e.printStackTrace();
}
return v;
}
/**
*
* @param rs
* @return
* @throws SQLException
*/
private static ValoracionMateria getEntidadFromResultSet (ResultSet rs) throws SQLException {
ValoracionMateria o = new ValoracionMateria();
o.setId(rs.getInt("id"));
o.setIdEstudiante(rs.getInt("idEstudiante"));
o.setIdMateria(rs.getInt("idMateria"));
o.setIdProfesor(rs.getInt("idProfesor"));
o.setValoracion(rs.getFloat("valoracion"));
return o;
}
}

View File

@@ -0,0 +1,5 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores;
public class SuperControlador {
}

View File

@@ -0,0 +1,51 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades;
public class Curso {
private int id;
private String descripcion;
public Curso() {
super();
}
public Curso(int id, String descripcion) {
super();
this.id = id;
this.descripcion = descripcion;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
@Override
public String toString() {
return descripcion;
}
}

View File

@@ -0,0 +1,29 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades;
public class Estudiante {
private int id;
private String nombre;
public Estudiante() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}

View File

@@ -0,0 +1,73 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades;
public class Materia {
private int id;
private int cursoId;
private String nombre;
private String acronimo;
public Materia() {
super();
}
public Materia(int id, int cursoId, String nombre, String acronimo) {
super();
this.id = id;
this.cursoId = cursoId;
this.nombre = nombre;
this.acronimo = acronimo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCursoId() {
return cursoId;
}
public void setCursoId(int cursoId) {
this.cursoId = cursoId;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getAcronimo() {
return acronimo;
}
public void setAcronimo(String acronimo) {
this.acronimo = acronimo;
}
@Override
public String toString() {
return nombre;
}
}

View File

@@ -0,0 +1,34 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades;
public class Profesor {
private int id;
private String nombre;
public Profesor() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
@Override
public String toString() {
return nombre;
}
}

View File

@@ -0,0 +1,51 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades;
public class ValoracionMateria {
private int id;
private int idProfesor;
private int idMateria;
private int idEstudiante;
private float valoracion;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIdProfesor() {
return idProfesor;
}
public void setIdProfesor(int idProfesor) {
this.idProfesor = idProfesor;
}
public int getIdMateria() {
return idMateria;
}
public void setIdMateria(int idMateria) {
this.idMateria = idMateria;
}
public int getIdEstudiante() {
return idEstudiante;
}
public void setIdEstudiante(int idEstudiante) {
this.idEstudiante = idEstudiante;
}
public float getValoracion() {
return valoracion;
}
public void setValoracion(float valoracion) {
this.valoracion = valoracion;
}
@Override
public String toString() {
return "ValoracionMateria [id=" + id + ", idProfesor=" + idProfesor + ", idMateria=" + idMateria
+ ", idEstudiante=" + idEstudiante + ", valoracion=" + valoracion + "]";
}
}

View File

@@ -0,0 +1,135 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores.ControladorCurso;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Curso;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Font;
import javax.swing.ImageIcon;
import java.awt.Insets;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PanelCurso extends JPanel {
private static final long serialVersionUID = 1L;
private JTextField jtfId;
private JTextField jtfDescripcion;
/**
* Create the panel.
*/
public PanelCurso() {
setLayout(new BorderLayout(0, 0));
JToolBar toolBar = new JToolBar();
add(toolBar, BorderLayout.NORTH);
JButton btnPrimero = new JButton("");
btnPrimero.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cargarPrimero();
}
});
btnPrimero.setIcon(new ImageIcon(PanelCurso.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/gotostart.png")));
toolBar.add(btnPrimero);
JButton btnAnterior = new JButton("");
btnAnterior.setIcon(new ImageIcon(PanelCurso.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/previous.png")));
toolBar.add(btnAnterior);
JButton btnSiguiente = new JButton("");
btnSiguiente.setIcon(new ImageIcon(PanelCurso.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/next.png")));
toolBar.add(btnSiguiente);
JButton btnUltimo = new JButton("");
btnUltimo.setIcon(new ImageIcon(PanelCurso.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/gotoend.png")));
toolBar.add(btnUltimo);
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Gestión de Curso");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 17));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridwidth = 2;
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
panel.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_2 = new JLabel("Id:");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_2.gridx = 0;
gbc_lblNewLabel_2.gridy = 1;
panel.add(lblNewLabel_2, gbc_lblNewLabel_2);
jtfId = new JTextField();
jtfId.setEnabled(false);
GridBagConstraints gbc_jtfId = new GridBagConstraints();
gbc_jtfId.insets = new Insets(0, 0, 5, 0);
gbc_jtfId.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfId.gridx = 1;
gbc_jtfId.gridy = 1;
panel.add(jtfId, gbc_jtfId);
jtfId.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Descripción:");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_1.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 2;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
jtfDescripcion = new JTextField();
GridBagConstraints gbc_jtfDescripcion = new GridBagConstraints();
gbc_jtfDescripcion.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfDescripcion.gridx = 1;
gbc_jtfDescripcion.gridy = 2;
panel.add(jtfDescripcion, gbc_jtfDescripcion);
jtfDescripcion.setColumns(10);
}
/**
*
*/
private void cargarPrimero() {
Curso o = ControladorCurso.getPrimero();
muestraEnPantalla(o);
}
private void muestraEnPantalla(Curso o) {
if (o != null) {
this.jtfId.setText("" + o.getId());
this.jtfDescripcion.setText(o.getDescripcion());
}
}
}

View File

@@ -0,0 +1,139 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Font;
import java.awt.Insets;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PanelDatosPersonales extends JPanel {
private static final long serialVersionUID = 1L;
private JTextField jtfId;
private JTextField jtfNombre;
private JLabel lblTitulo;
private Runnable runnableMostrarPrimerRegistro;
/**
* Create the panel.
*/
public PanelDatosPersonales() {
setLayout(new BorderLayout(0, 0));
JToolBar toolBar = new JToolBar();
add(toolBar, BorderLayout.NORTH);
JButton btnPrimero = new JButton("");
btnPrimero.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
runnableMostrarPrimerRegistro.run();
}
});
btnPrimero.setIcon(new ImageIcon(PanelDatosPersonales.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/gotostart.png")));
toolBar.add(btnPrimero);
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
lblTitulo = new JLabel("Título del componente");
lblTitulo.setFont(new Font("Tahoma", Font.BOLD, 17));
GridBagConstraints gbc_lblTitulo = new GridBagConstraints();
gbc_lblTitulo.insets = new Insets(0, 0, 5, 0);
gbc_lblTitulo.gridwidth = 2;
gbc_lblTitulo.gridx = 0;
gbc_lblTitulo.gridy = 0;
panel.add(lblTitulo, gbc_lblTitulo);
JLabel lblNewLabel_1 = new JLabel("Id:");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 1;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
jtfId = new JTextField();
GridBagConstraints gbc_jtfId = new GridBagConstraints();
gbc_jtfId.insets = new Insets(0, 0, 5, 0);
gbc_jtfId.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfId.gridx = 1;
gbc_jtfId.gridy = 1;
panel.add(jtfId, gbc_jtfId);
jtfId.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("Nombre:");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_2.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_2.gridx = 0;
gbc_lblNewLabel_2.gridy = 2;
panel.add(lblNewLabel_2, gbc_lblNewLabel_2);
jtfNombre = new JTextField();
GridBagConstraints gbc_jtfNombre = new GridBagConstraints();
gbc_jtfNombre.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfNombre.gridx = 1;
gbc_jtfNombre.gridy = 2;
panel.add(jtfNombre, gbc_jtfNombre);
jtfNombre.setColumns(10);
}
/**
*
* @param newTitulo
*/
public void setTitulo(String newTitulo) {
this.lblTitulo.setText(newTitulo);
}
/**
*
* @param id
*/
public void setId (int id) {
this.jtfId.setText("" + id);
}
/**
*
* @return
*/
public int getId () {
return Integer.parseInt(this.jtfId.getText());
}
public Runnable getRunnableMostrarPrimerRegistro() {
return runnableMostrarPrimerRegistro;
}
public void setRunnableMostrarPrimerRegistro(Runnable runnableMostrarPrimerRegistro) {
this.runnableMostrarPrimerRegistro = runnableMostrarPrimerRegistro;
}
}

View File

@@ -0,0 +1,53 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista;
import javax.swing.JPanel;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Estudiante;
import java.awt.BorderLayout;
public class PanelEstudiante extends JPanel {
private static final long serialVersionUID = 1L;
private PanelDatosPersonales panelDatos = new PanelDatosPersonales();
/**
* Create the panel.
*/
public PanelEstudiante() {
setLayout(new BorderLayout(0, 0));
this.add(panelDatos, BorderLayout.CENTER);
this.panelDatos.setTitulo("Gestión de estudiantes");
this.panelDatos.setRunnableMostrarPrimerRegistro(
new Runnable() {
@Override
public void run() {
mostrarPrimero();
}
});
}
private void mostrarPrimero() {
// En teoría aquí se produce una llamada a un controlador de estudiante
// que obtiene un objeto de tipo estudiante y que lo envía para ser
// mostrado
Estudiante mockEstudiante = new Estudiante();
mockEstudiante.setId(1);
mockEstudiante.setNombre("Rafa");
mostrarEntidad(mockEstudiante);
}
private void mostrarEntidad(Estudiante e) {
this.panelDatos.setId(e.getId());
}
}

View File

@@ -0,0 +1,199 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores.ControladorCurso;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores.ControladorMateria;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Curso;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Materia;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Font;
import javax.swing.ImageIcon;
import java.awt.Insets;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
public class PanelMateria extends JPanel {
private static final long serialVersionUID = 1L;
private JTextField jtfId;
private JTextField jtfAcronimo;
private JTextField jtfNombre;
private JComboBox<Curso> jcbCurso;
/**
* Create the panel.
*/
public PanelMateria() {
setLayout(new BorderLayout(0, 0));
JToolBar toolBar = new JToolBar();
add(toolBar, BorderLayout.NORTH);
JButton btnPrimero = new JButton("");
btnPrimero.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cargarPrimero();
}
});
btnPrimero.setIcon(new ImageIcon(PanelMateria.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/gotostart.png")));
toolBar.add(btnPrimero);
JButton btnAnterior = new JButton("");
btnAnterior.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Curso id seleccionado: " +
((Curso) jcbCurso.getSelectedItem()).getId());
}
});
btnAnterior.setIcon(new ImageIcon(PanelMateria.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/previous.png")));
toolBar.add(btnAnterior);
JButton btnSiguiente = new JButton("");
btnSiguiente.setIcon(new ImageIcon(PanelMateria.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/next.png")));
toolBar.add(btnSiguiente);
JButton btnUltimo = new JButton("");
btnUltimo.setIcon(new ImageIcon(PanelMateria.class.getResource("/tutorialJava/capitulo9_AWT_SWING/res/gotoend.png")));
toolBar.add(btnUltimo);
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Gestión de Materia");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 17));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridwidth = 2;
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
panel.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_2 = new JLabel("Id:");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_2.gridx = 0;
gbc_lblNewLabel_2.gridy = 1;
panel.add(lblNewLabel_2, gbc_lblNewLabel_2);
jtfId = new JTextField();
jtfId.setEnabled(false);
GridBagConstraints gbc_jtfId = new GridBagConstraints();
gbc_jtfId.insets = new Insets(0, 0, 5, 0);
gbc_jtfId.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfId.gridx = 1;
gbc_jtfId.gridy = 1;
panel.add(jtfId, gbc_jtfId);
jtfId.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Curso:");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 2;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
jcbCurso = new JComboBox<Curso>();
GridBagConstraints gbc_jcbCurso = new GridBagConstraints();
gbc_jcbCurso.insets = new Insets(0, 0, 5, 0);
gbc_jcbCurso.fill = GridBagConstraints.HORIZONTAL;
gbc_jcbCurso.gridx = 1;
gbc_jcbCurso.gridy = 2;
panel.add(jcbCurso, gbc_jcbCurso);
JLabel lblNewLabel_3 = new JLabel("Acrónimo:");
GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
gbc_lblNewLabel_3.anchor = GridBagConstraints.ABOVE_BASELINE_TRAILING;
gbc_lblNewLabel_3.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_3.gridx = 0;
gbc_lblNewLabel_3.gridy = 3;
panel.add(lblNewLabel_3, gbc_lblNewLabel_3);
jtfAcronimo = new JTextField();
GridBagConstraints gbc_jtfAcronimo = new GridBagConstraints();
gbc_jtfAcronimo.insets = new Insets(0, 0, 5, 0);
gbc_jtfAcronimo.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfAcronimo.gridx = 1;
gbc_jtfAcronimo.gridy = 3;
panel.add(jtfAcronimo, gbc_jtfAcronimo);
jtfAcronimo.setColumns(10);
JLabel lblNewLabel_4 = new JLabel("Nombre:");
GridBagConstraints gbc_lblNewLabel_4 = new GridBagConstraints();
gbc_lblNewLabel_4.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_4.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_4.gridx = 0;
gbc_lblNewLabel_4.gridy = 4;
panel.add(lblNewLabel_4, gbc_lblNewLabel_4);
jtfNombre = new JTextField();
GridBagConstraints gbc_jtfNombre = new GridBagConstraints();
gbc_jtfNombre.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfNombre.gridx = 1;
gbc_jtfNombre.gridy = 4;
panel.add(jtfNombre, gbc_jtfNombre);
jtfNombre.setColumns(10);
// Cargo todos los cursos en el jcombo
cargarTodosCursos();
cargarPrimero();
}
private void cargarTodosCursos () {
List<Curso> l = ControladorCurso.getTodos();
for (Curso o : l) {
jcbCurso.addItem(o);
}
}
/**
*
*/
private void cargarPrimero() {
Materia o = ControladorMateria.getPrimero();
muestraEnPantalla(o);
}
private void muestraEnPantalla(Materia o) {
if (o != null) {
this.jtfId.setText("" + o.getId());
for (int i = 0; i < jcbCurso.getItemCount(); i++) {
if (jcbCurso.getItemAt(i).getId() == o.getCursoId()) {
jcbCurso.setSelectedIndex(i);
}
}
this.jtfAcronimo.setText(o.getAcronimo());
this.jtfNombre.setText(o.getNombre());
}
}
}

View File

@@ -0,0 +1,92 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores.ControladorValoracionMateria;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Estudiante;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Materia;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Profesor;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.ValoracionMateria;
import java.awt.Insets;
public class PanelSlotEvaluacionEstudiante extends JPanel {
private static final long serialVersionUID = 1L;
private JTextField jtfValoracion;
private Profesor profesor;
private Materia materia;
private Estudiante estudiante;
/**
* Create the panel.
*/
public PanelSlotEvaluacionEstudiante(Profesor p, Estudiante e, Materia m) {
this.profesor = p;
this.estudiante = e;
this.materia = m;
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel lblNombreEstudiante = new JLabel("New label");
GridBagConstraints gbc_lblNombreEstudiante = new GridBagConstraints();
gbc_lblNombreEstudiante.insets = new Insets(0, 0, 0, 5);
gbc_lblNombreEstudiante.anchor = GridBagConstraints.EAST;
gbc_lblNombreEstudiante.gridx = 0;
gbc_lblNombreEstudiante.gridy = 0;
add(lblNombreEstudiante, gbc_lblNombreEstudiante);
jtfValoracion = new JTextField();
GridBagConstraints gbc_jtfValoracion = new GridBagConstraints();
gbc_jtfValoracion.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfValoracion.gridx = 1;
gbc_jtfValoracion.gridy = 0;
add(jtfValoracion, gbc_jtfValoracion);
jtfValoracion.setColumns(10);
// Establezco valores iniciales
lblNombreEstudiante.setText(this.estudiante.getNombre());
cargarNotaActual();
}
/**
*
*/
private void cargarNotaActual() {
ValoracionMateria v =
ControladorValoracionMateria.findByIdMateriaAndIdProfesorAndIdEstudiante(
this.materia.getId(), this.profesor.getId(), this.estudiante.getId());
if (v != null) {
this.jtfValoracion.setText("" + v.getValoracion());
}
}
public void guardarNota() {
}
}

View File

@@ -0,0 +1,189 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.vista;
import javax.swing.JPanel;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores.ControladorEstudiante;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores.ControladorMateria;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.controladores.ControladorProfesor;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Estudiante;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Materia;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemplo02_GestionCentroEducativo.entitidades.Profesor;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.BoxLayout;
public class PanelValoracionMateriaOpcion1 extends JPanel {
private static final long serialVersionUID = 1L;
JComboBox<Materia> jcbMateria;
JComboBox<Profesor> jcbProfesor;
JPanel panelEstudiantes;
List<PanelSlotEvaluacionEstudiante> listaSlotsValoracion = new ArrayList<PanelSlotEvaluacionEstudiante>();
/**
* Create the panel.
*/
public PanelValoracionMateriaOpcion1() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowWeights = new double[]{0.0, 1.0, 0.0};
gridBagLayout.columnWeights = new double[]{1.0};
setLayout(gridBagLayout);
JPanel panelProfesorMateria = new JPanel();
GridBagConstraints gbc_panelProfesorMateria = new GridBagConstraints();
gbc_panelProfesorMateria.insets = new Insets(0, 0, 5, 0);
gbc_panelProfesorMateria.fill = GridBagConstraints.BOTH;
gbc_panelProfesorMateria.gridx = 0;
gbc_panelProfesorMateria.gridy = 0;
add(panelProfesorMateria, gbc_panelProfesorMateria);
GridBagLayout gbl_panelProfesorMateria = new GridBagLayout();
gbl_panelProfesorMateria.columnWidths = new int[]{0, 0, 0, 0};
gbl_panelProfesorMateria.rowHeights = new int[]{0, 0, 0, 0};
gbl_panelProfesorMateria.columnWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
gbl_panelProfesorMateria.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
panelProfesorMateria.setLayout(gbl_panelProfesorMateria);
JLabel lblNewLabel = new JLabel("Materia:");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
panelProfesorMateria.add(lblNewLabel, gbc_lblNewLabel);
jcbMateria = new JComboBox<Materia>();
GridBagConstraints gbc_jcbMateria = new GridBagConstraints();
gbc_jcbMateria.insets = new Insets(0, 0, 5, 5);
gbc_jcbMateria.fill = GridBagConstraints.HORIZONTAL;
gbc_jcbMateria.gridx = 1;
gbc_jcbMateria.gridy = 0;
panelProfesorMateria.add(jcbMateria, gbc_jcbMateria);
JLabel lblNewLabel_1 = new JLabel("Profesor:");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 1;
panelProfesorMateria.add(lblNewLabel_1, gbc_lblNewLabel_1);
jcbProfesor = new JComboBox<Profesor>();
GridBagConstraints gbc_jcbProfesor = new GridBagConstraints();
gbc_jcbProfesor.insets = new Insets(0, 0, 5, 5);
gbc_jcbProfesor.fill = GridBagConstraints.HORIZONTAL;
gbc_jcbProfesor.gridx = 1;
gbc_jcbProfesor.gridy = 1;
panelProfesorMateria.add(jcbProfesor, gbc_jcbProfesor);
JButton btnRefrescar = new JButton("Refrescar");
btnRefrescar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
refrescarEstudiantes();
}
});
GridBagConstraints gbc_btnRefrescar = new GridBagConstraints();
gbc_btnRefrescar.gridx = 2;
gbc_btnRefrescar.gridy = 2;
panelProfesorMateria.add(btnRefrescar, gbc_btnRefrescar);
panelEstudiantes = new JPanel();
GridBagConstraints gbc_panelEstudiantes = new GridBagConstraints();
gbc_panelEstudiantes.weighty = 1.0;
gbc_panelEstudiantes.insets = new Insets(0, 0, 5, 0);
gbc_panelEstudiantes.fill = GridBagConstraints.BOTH;
gbc_panelEstudiantes.gridx = 0;
gbc_panelEstudiantes.gridy = 1;
add(panelEstudiantes, gbc_panelEstudiantes);
panelEstudiantes.setLayout(new BoxLayout(panelEstudiantes, BoxLayout.Y_AXIS));
JButton btnGuardar = new JButton("Guardar");
btnGuardar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
guardar();
}
});
GridBagConstraints gbc_btnGuardar = new GridBagConstraints();
gbc_btnGuardar.anchor = GridBagConstraints.EAST;
gbc_btnGuardar.gridx = 0;
gbc_btnGuardar.gridy = 2;
add(btnGuardar, gbc_btnGuardar);
cargarTodasMaterias();
cargarTodProfesores();
}
private void cargarTodasMaterias() {
List<Materia> l = ControladorMateria.getTodos();
for (Materia m : l) {
this.jcbMateria.addItem(m);
}
}
private void cargarTodProfesores() {
List<Profesor> l = ControladorProfesor.getTodos();
for (Profesor p : l) {
this.jcbProfesor.addItem(p);
}
}
private void refrescarEstudiantes() {
List<Estudiante> l = ControladorEstudiante.getTodos();
Profesor profSeleccionado = (Profesor) this.jcbProfesor.getSelectedItem();
Materia matSeleccionada = (Materia) this.jcbMateria.getSelectedItem();
this.panelEstudiantes.removeAll();
this.listaSlotsValoracion.clear();
for(Estudiante e : l) {
PanelSlotEvaluacionEstudiante slot =
new PanelSlotEvaluacionEstudiante(profSeleccionado, e, matSeleccionada);
this.listaSlotsValoracion.add(slot);
this.panelEstudiantes.add(slot);
}
this.panelEstudiantes.revalidate();
this.panelEstudiantes.repaint();
}
/**
*
*/
private void guardar() {
for(PanelSlotEvaluacionEstudiante panel : this.listaSlotsValoracion) {
panel.guardarNota();
}
}
}

View File

@@ -0,0 +1,50 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemploPanelDentroDeDialogo;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JComboBox;
public class PanelDentroDeDialogo extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public PanelDentroDeDialogo() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel lblNewLabel = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
add(lblNewLabel, gbc_lblNewLabel);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 1;
add(textField, gbc_textField);
textField.setColumns(10);
JComboBox comboBox = new JComboBox();
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 0;
gbc_comboBox.gridy = 2;
add(comboBox, gbc_comboBox);
}
}

View File

@@ -0,0 +1,89 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.ejemploPanelDentroDeDialogo;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JDialog;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class VentanaPrincipal extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VentanaPrincipal frame = new VentanaPrincipal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public VentanaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
abrirNuevoDialogo();
}
});
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 0;
contentPane.add(btnNewButton, gbc_btnNewButton);
}
/**
*
*/
public void abrirNuevoDialogo() {
JDialog dialogo = new JDialog();
// El usuario no puede redimensionar el di<64>logo
dialogo.setResizable(true);
// t<>tulo del d<>alogo
dialogo.setTitle("Gestión de empresas");
// Introducimos el panel creado sobre el di<64>logo
dialogo.setContentPane(new PanelDentroDeDialogo());
// Empaquetar el di<64>logo hace que todos los componentes ocupen el espacio que deben y el lugar adecuado
dialogo.pack();
// El usuario no puede hacer clic sobre la ventana padre, si el Di<44>logo es modal
dialogo.setModal(true);
// Centro el di<64>logo en pantalla
dialogo.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/2 - dialogo.getWidth()/2,
(Toolkit.getDefaultToolkit().getScreenSize().height)/2 - dialogo.getHeight()/2);
// Muestro el di<64>logo en pantalla
dialogo.setVisible(true);
}
}

View File

@@ -0,0 +1,56 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JRadioButton;
public class MiJRadioButtonKk extends JRadioButton {
int idDisciplina;
public MiJRadioButtonKk() {
}
public MiJRadioButtonKk(int idDisciplina) {
this.idDisciplina = idDisciplina;
}
public MiJRadioButtonKk(Icon icon) {
super(icon);
}
public MiJRadioButtonKk(Action a) {
super(a);
}
public MiJRadioButtonKk(String text) {
super(text);
}
public MiJRadioButtonKk(Icon icon, boolean selected) {
super(icon, selected);
}
public MiJRadioButtonKk(String text, boolean selected) {
super(text, selected);
}
public MiJRadioButtonKk(String text, Icon icon) {
super(text, icon);
}
public MiJRadioButtonKk(String text, Icon icon, boolean selected) {
super(text, icon, selected);
}
public int getIdDisciplina() {
return idDisciplina;
}
public void setIdDisciplina(int idDisciplina) {
this.idDisciplina = idDisciplina;
}
}

View File

@@ -0,0 +1,30 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.controller;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.model.Est;
public class EstudianteControlador {
private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("CentroEducativo");
public static List<Est> findAll() {
EntityManager em = entityManagerFactory.createEntityManager();
Query q = em.createNativeQuery("SELECT * FROM estudiante;", Est.class);
List<Est> l = (List<Est>) q.getResultList();
em.close();
return l;
}
}

View File

@@ -0,0 +1,123 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the estudiante database table.
*
*/
@Entity
@Table(name="estudiante")
@NamedQuery(name="Est.findAll", query="SELECT e FROM Est e")
public class Est implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String apellido1;
private String apellido2;
private String direccion;
private String dni;
private String email;
private int idTipologiaSexo;
@Lob
private byte[] imagen;
private String nombre;
private String telefono;
public Est() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getApellido1() {
return this.apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return this.apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
public String getDireccion() {
return this.direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getDni() {
return this.dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public int getIdTipologiaSexo() {
return this.idTipologiaSexo;
}
public void setIdTipologiaSexo(int idTipologiaSexo) {
this.idTipologiaSexo = idTipologiaSexo;
}
public byte[] getImagen() {
return this.imagen;
}
public void setImagen(byte[] imagen) {
this.imagen = imagen;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
}

View File

@@ -0,0 +1,108 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.view;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JTextField;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.model.Est;
public class PanelGestionEstudiante extends JPanel {
private JTextField jtfId;
private JTextField jtfNombre;
private JTextField jtfApellido1;
private JTextField jtfApellido2;
/**
* Create the panel.
*/
public PanelGestionEstudiante() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel lblNewLabel = new JLabel("Id:");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
add(lblNewLabel, gbc_lblNewLabel);
jtfId = new JTextField();
GridBagConstraints gbc_jtfId = new GridBagConstraints();
gbc_jtfId.insets = new Insets(0, 0, 5, 0);
gbc_jtfId.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfId.gridx = 1;
gbc_jtfId.gridy = 0;
add(jtfId, gbc_jtfId);
jtfId.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Nombre:");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 1;
add(lblNewLabel_1, gbc_lblNewLabel_1);
jtfNombre = new JTextField();
GridBagConstraints gbc_jtfNombre = new GridBagConstraints();
gbc_jtfNombre.insets = new Insets(0, 0, 5, 0);
gbc_jtfNombre.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfNombre.gridx = 1;
gbc_jtfNombre.gridy = 1;
add(jtfNombre, gbc_jtfNombre);
jtfNombre.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("Primer apellido:");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_2.gridx = 0;
gbc_lblNewLabel_2.gridy = 2;
add(lblNewLabel_2, gbc_lblNewLabel_2);
jtfApellido1 = new JTextField();
GridBagConstraints gbc_jtfApellido1 = new GridBagConstraints();
gbc_jtfApellido1.insets = new Insets(0, 0, 5, 0);
gbc_jtfApellido1.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfApellido1.gridx = 1;
gbc_jtfApellido1.gridy = 2;
add(jtfApellido1, gbc_jtfApellido1);
jtfApellido1.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("Segundo apellido:");
GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
gbc_lblNewLabel_3.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_3.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_3.gridx = 0;
gbc_lblNewLabel_3.gridy = 3;
add(lblNewLabel_3, gbc_lblNewLabel_3);
jtfApellido2 = new JTextField();
GridBagConstraints gbc_jtfApellido2 = new GridBagConstraints();
gbc_jtfApellido2.fill = GridBagConstraints.HORIZONTAL;
gbc_jtfApellido2.gridx = 1;
gbc_jtfApellido2.gridy = 3;
add(jtfApellido2, gbc_jtfApellido2);
jtfApellido2.setColumns(10);
}
/**
*
*/
public void setEstudiante(Est e) {
this.jtfId.setText("" + e.getId());
this.jtfNombre.setText(e.getNombre());
this.jtfApellido1.setText(e.getApellido1());
this.jtfApellido2.setText(e.getApellido2());
}
}

View File

@@ -0,0 +1,68 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.view;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.controller.EstudianteControlador;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.model.Est;
public class Tabla extends JPanel {
List<Est> estudiantes = new ArrayList<Est>();
JTable table = null;
/**
*
*/
public Tabla () {
//Creo un objeto JTable con el constructor m<>s sencillo del que dispone
table = new JTable(getDatosDeTabla(),
new String[] {"Id", "Nombre", "Primer apellido", "Segundo apellido"});
//Creamos un JscrollPane y le agregamos la JTable
JScrollPane scrollPane = new JScrollPane(table);
// Accedo a los clics realizados sobre la tabla
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if (e.getButton() == MouseEvent.BUTTON1) {
VentanaPrincipal.getInstance().getPanelGestionEstudiante()
.setEstudiante(estudiantes.get(table.getSelectedRow()));
}
}
});
//Agregamos el JScrollPane al contenedor
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}
/**
*
* @return
*/
private Object[][] getDatosDeTabla() {
estudiantes = EstudianteControlador.findAll();
Object[][] matrizDatos = new Object[estudiantes.size()][4];
for (int i = 0; i < estudiantes.size(); i++) {
matrizDatos[i][0] = estudiantes.get(i).getId();
matrizDatos[i][1] = estudiantes.get(i).getNombre();
matrizDatos[i][2] = estudiantes.get(i).getApellido1();
matrizDatos[i][3] = estudiantes.get(i).getApellido2();
}
return matrizDatos;
}
}

View File

@@ -0,0 +1,97 @@
package tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.view;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.controller.EstudianteControlador;
import tutorialJava.capitulo9_AWT_SWING.ejemplos.jTableEstudiantes.model.Est;
import javax.swing.JSplitPane;
import java.awt.GridBagLayout;
import java.util.List;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
public class VentanaPrincipal extends JFrame {
private JPanel contentPane;
private PanelGestionEstudiante panelGestionEstudiante = new PanelGestionEstudiante();
private Tabla tabla = new Tabla();
private static VentanaPrincipal singleton = null;
/**
*
* @return
*/
public static VentanaPrincipal getInstance() {
if (singleton == null) {
singleton = new VentanaPrincipal();
}
return singleton;
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EstudianteControlador.findAll();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VentanaPrincipal.getInstance().setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public VentanaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JSplitPane splitPane = new JSplitPane();
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
GridBagConstraints gbc_splitPane = new GridBagConstraints();
gbc_splitPane.fill = GridBagConstraints.BOTH;
gbc_splitPane.gridx = 0;
gbc_splitPane.gridy = 0;
contentPane.add(splitPane, gbc_splitPane);
tabla.setMinimumSize(new Dimension(100, 100));
splitPane.setLeftComponent(tabla);
// splitPane.setDividerLocation(0.7);
splitPane.setRightComponent(panelGestionEstudiante);
}
public PanelGestionEstudiante getPanelGestionEstudiante() {
return panelGestionEstudiante;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 600 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 894 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 440 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 589 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 638 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 314 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 241 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 576 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 492 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Some files were not shown because too many files have changed in this diff Show More