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

@@ -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
* @return Número entero introducido a través de un JOptionPane.
@@ -143,6 +161,11 @@ public class Utils {
return num;
}
public static double obtenerDoubleConDescripcion(String desc) {
System.out.println(desc);
return obtenerDoublePorScanner();
}
/**
*
* @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<61>metros de conexi<78>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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,67 @@
package tutorialJava.capitulo9_AWT_SWING.utils;
import javax.swing.UIManager;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
public class Apariencia {
public static int SO_ANFITRION = 0;
public static int METAL = 1;
public static int GTK = 2;
public static int MOTIF = 3;
public static int WINDOWS = 4;
public static int OCEAN = 5;
public static int aparienciasOrdenadas[] = new int[] {WINDOWS, OCEAN, METAL, MOTIF, GTK};
/**
*
*/
public static void setApariencia (int apariencia) throws Exception {
switch (apariencia) {
case 0: // SO_ANFITRION
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // Look and Feel del sistema operativo instalado
break;
case 1: // METAL
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); // L&F c<>silo Java, llamado "Metal"
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
//MetalLookAndFeel.setCurrentTheme(new OceanTheme());
break;
case 2: // GTK
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); // Look and Feel GTK - S<>lo en entornos Linux, Unix y Solaris
break;
case 3: // MOTIF
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); // Look and Feel Motif
break;
case 4: // WINDOWS
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // Look and Feel Windows - S<>lo en entornos Windows
break;
case 5: // OCEAN
UIManager.setLookAndFeel("javax.swing.plaf.metal.OceanTheme"); // Look and Feel Ocean
break;
}
}
/**
*
* @param apariencias
*/
public static void setAparienciasOrdenadas (int apariencias[]) {
// Por cada apariencia intento ponerla salvo que obtengamos un error, si lo obtengo paso a la siguiente apariencia
int i = 0;
boolean falloAlCargarApariencia;
do {
falloAlCargarApariencia = false;
try {
setApariencia(apariencias[i]);
}
catch (Exception ex) {
i++;
falloAlCargarApariencia = true;
}
} while (falloAlCargarApariencia);
}
}

View File

@@ -0,0 +1,63 @@
package tutorialJava.capitulo9_AWT_SWING.utils;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class CacheImagenes extends CacheRecursos implements ImageObserver{
private static CacheImagenes cacheImagenes = null;
public static CacheImagenes getCacheImagenes () {
if (cacheImagenes == null) {
cacheImagenes = new CacheImagenes();
}
return cacheImagenes;
}
protected Object loadResource(URL url) {
try {
return ImageIO.read(url);
} catch (Exception e) {
e.printStackTrace();
System.out.println("No se pudo cargar la imagen de "+url);
System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
System.exit(0);
return null;
}
}
private BufferedImage crearCompatible(int width, int height, int transparency) {
GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
BufferedImage compatible = gc.createCompatibleImage(width,height,transparency);
return compatible;
}
public BufferedImage getImagen(String name) {
BufferedImage loaded = (BufferedImage)getResource(name);
BufferedImage compatible = crearCompatible(loaded.getWidth(),loaded.getHeight(),Transparency.BITMASK);
Graphics g = compatible.getGraphics();
g.drawImage(loaded,0,0,this);
return compatible;
}
public ImageIcon getIcono (String name) {
return new ImageIcon (getImagen(name));
}
public boolean imageUpdate(Image img, int infoflags,int x, int y, int w, int h) {
return (infoflags & (ALLBITS|ABORT)) == 0;
}
}

View File

@@ -0,0 +1,30 @@
package tutorialJava.capitulo9_AWT_SWING.utils;
import java.net.URL;
import java.util.HashMap;
public abstract class CacheRecursos {
protected HashMap resources;
public CacheRecursos() {
resources = new HashMap();
}
protected Object loadResource(String name) {
URL url=null;
url = getClass().getClassLoader().getResource(name);
return loadResource(url);
}
protected Object getResource(String name) {
Object res = resources.get(name);
if (res == null) {
res = loadResource("tutorialJava/capitulo9_AWT_SWING/res/" + name);
resources.put (name,res);
}
return res;
}
protected abstract Object loadResource(URL url);
}

View File

@@ -0,0 +1,13 @@
package tutorialJava.capitulo9_AWT_SWING.v01_PrimeraVentanaMouseListeners;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
VentanaPrincipal ventanaPrincipal = new VentanaPrincipal ();
ventanaPrincipal.setVisible(true);
}
}

View File

@@ -0,0 +1,50 @@
package tutorialJava.capitulo9_AWT_SWING.v01_PrimeraVentanaMouseListeners;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class MyWindowListener implements WindowListener{
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
}

View File

@@ -0,0 +1,238 @@
package tutorialJava.capitulo9_AWT_SWING.v01_PrimeraVentanaMouseListeners;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import tutorialJava.capitulo9_AWT_SWING.utils.Apariencia;
import tutorialJava.capitulo9_AWT_SWING.utils.CacheImagenes;
public class VentanaPrincipal extends JFrame {
public static int ANCHO = 800;
public static int ALTO = 600;
public static String TITULO_APLICACION = "Título de la aplicación";
private CacheImagenes cacheImagenes;
public static BufferedImage iconoApp;
// Establecer la apariencia típica de Windows
static {
Apariencia.setAparienciasOrdenadas(Apariencia.aparienciasOrdenadas);
}
public VentanaPrincipal () {
super (TITULO_APLICACION);
cacheImagenes = new CacheImagenes();
iconoApp = cacheImagenes.getImagen("nave.gif");
this.setIconImage(iconoApp);
// Tamaño por defecto, basado en los valores estéticos de esta misma clase
setDimensionesBasicas();
// Una posibilidad es iniciar el JFrame en un estado determinado, las opciones son:
// JFrame.NORMAL: Inicializa el JFrame en estado Normal
// JFrame.ICONIFIED: Inicializa el JFrame en estado Minimizado.
// JFrame.MAXIMIZED_HORIZ: Inicializa el JFrame en estado Maximizado Horizontalmente
// JFrame.MAXIMIZED_VERT: Inicializa el JFrame en estado Maximizado Verticalmente
// JFrame.MAXIMIZED_BOTH: Inicializa el JFrame en estado Maximizado en ambos sentidos
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Configuración del evento de cerrado
// Para más información debes estudiar Javadoc WindowListener y WindowAdapter
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
String posiblesRespuestas[] = {"","No"};
// En esta opción se utiliza un showOptionDialog en el que personalizo el icono mostrado
int opcionElegida = JOptionPane.showOptionDialog(
null,
"¿Realmente desea cerrar la aplicación?",
TITULO_APLICACION,
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
cacheImagenes.getIcono("confirm.png"),
posiblesRespuestas,
posiblesRespuestas[1]);
if(opcionElegida == 0) {
System.exit(0);
}
}
});
// Inclusión de los eventos de teclado
// Para más información debes estudiar Javadoc KeyListener y KeyAdapter
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// En esta ocasión he decidido no personalizar el icono mostrado, para obtener el icono por defecto
JOptionPane.showMessageDialog(null, "Deja de pulsar teclas ya", TITULO_APLICACION, JOptionPane.INFORMATION_MESSAGE, null);
}
});
// incluimos y estudiamos los eventos del rat<61>n
inclusionEventosRaton();
// Construcción elementos básicos sobre el ContentPanel
this.setContentPane(getElementosBasicosPanel());
}
/**
*
*/
private void setDimensionesBasicas () {
this.setExtendedState(JFrame.NORMAL);
this.setBounds(0, 0, ANCHO, ALTO);
this.setMinimumSize(new Dimension(ANCHO, ALTO));
}
/**
*
*/
private void inclusionEventosRaton () {
// MouseListener permite controlar eventos de rat<61>n simples
this.addMouseListener(new MouseListener () {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Botón de ratón pulsado: " + e.getButton() + " - " + e.getClickCount() + " veces");
System.out.println("\tX: " + e.getX() + " Y: " + e.getY() + " X en pantalla: " + e.getXOnScreen() + " Y en pantalla: " + e.getYOnScreen());
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Botón de ratón presionado: " + e.getButton());
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Botón de ratón liberado: " + e.getButton());
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("Ratón entra en la ventana");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("Ratón sale de la ventana");
}
});
// Los eventos del MouseMotionListener nos permiten detectar movimiento del ratón y arrastre, a bajo nivel
this.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("Ratón se ha desplazado a las coordenadas x: " + e.getX() + " y: " + e.getY());
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Ratón arrastrando a las coordenadas x: " + e.getX() + " y: " + e.getY());
}
});
// Por último, algo muy habitual
this.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getWheelRotation() > 0) {
System.out.println("Movimiento de reducción - Rueda hacía atrás - Pasos: " + e.getWheelRotation());
}
else {
System.out.println("Movimiento de amplitud - Rueda hacía adelante - Pasos: " + e.getWheelRotation());
}
}
});
}
/**
*
*/
// Una web muy interesante para obtener un showcase de los componentes SWING es http://web.mit.edu/6.005/www/sp14/psets/ps4/java-6-tutorial/components.html
private JPanel getElementosBasicosPanel () {
JPanel muestrario = new JPanel();
// JLabel
JLabel lb = new JLabel ("Ejemplo de JTextField: ");
muestrario.add(lb);
// JTextField
JTextField tf = new JTextField("asdf");
tf.setText("Texto en el interior");
tf.setColumns(40);
tf.setToolTipText("ToolTip para el componente JTextField");
muestrario.add(tf);
// JButton
JButton bt = new JButton("Acción!!!");
bt.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseEntered(e);
System.out.println("Entrado en el botón");
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseExited(e);
System.out.println("Saliendo en el botón");
}
});
bt.addActionListener(new ActionListener () {
@Override
public void actionPerformed(ActionEvent e) {
// Personalización del icono, otra vez
JOptionPane.showMessageDialog(null, "Acción!!!!!!!", TITULO_APLICACION, JOptionPane.INFORMATION_MESSAGE, cacheImagenes.getIcono("goku.png"));
}
});
muestrario.add(bt);
return muestrario;
}
}

View File

@@ -0,0 +1,138 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CardLayoutEjemplo extends JPanel {
CardLayout cardLayout;
JPanel pnlSup, pnlInf, pnlInfOpcion1, pnlInfOpcion2, pnlInfOpcion3;
JComboBox jcb;
/**
*
*/
public CardLayoutEjemplo () {
super();
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
construyePanelSuperior();
construyePanelInf1();
construyePanelInf2();
construyePanelInf3();
construyePanelInferior();
this.add(pnlSup);
this.add(pnlInf);
}
/**
*
*/
public void construyePanelSuperior(){
pnlSup = new JPanel();
pnlSup.setBorder(BorderFactory.createTitledBorder("Ejemplo de CardLayout"));
pnlSup.setLayout(new FlowLayout());
pnlSup.add(JLabelFactory.instance("Elegir Opci<63>n"));
jcb = JComboBoxFactory.instance(new String[] {"Panel 1", "Panel 2", "Panel 3"});
jcb.addActionListener(new ActionListener () {
@Override
public void actionPerformed(ActionEvent e) {
if (jcb.getSelectedIndex() == 0){
cardLayout.show(pnlInf, "pnlInfOpcion1");
}
if (jcb.getSelectedIndex() == 1){
cardLayout.show(pnlInf, "pnlInfOpcion2");
}
if (jcb.getSelectedIndex()==2){
cardLayout.show(pnlInf, "pnlInfOpcion3");
}
}});
pnlSup.add(jcb);
}
/**
*
*/
public void construyePanelInferior(){
pnlInf = new JPanel();
pnlInf.setBorder(BorderFactory.createTitledBorder("Panel Inferior"));
cardLayout = new CardLayout();
pnlInf.setLayout(cardLayout);
/*Al agregar necesitamos 2 argumentos, el objeto a agregar y un nombre referencial */
pnlInf.add(pnlInfOpcion1, "pnlInfOpcion1");
pnlInf.add(pnlInfOpcion2, "pnlInfOpcion2");
pnlInf.add(pnlInfOpcion3, "pnlInfOpcion3");
}
/**
*
*/
public void construyePanelInf1(){
pnlInfOpcion1 = new JPanel(new FlowLayout());
pnlInfOpcion1.setBackground(Color.white);
pnlInfOpcion1.add(JLabelFactory.instance("Has Seleccionado el Panel 1"));
}
/**
*
*/
public void construyePanelInf2(){
pnlInfOpcion2 = new JPanel(new FlowLayout());
pnlInfOpcion2.setBackground(Color.orange);
pnlInfOpcion2.add(JLabelFactory.instance("Has Seleccionado el Panel 2. Magia!!!!"));
}
/**
*
*/
public void construyePanelInf3(){
pnlInfOpcion3 = new JPanel(new FlowLayout());
pnlInfOpcion3.setBackground(Color.green);
pnlInfOpcion3.add(JLabelFactory.instance("Increíble!!!!. Has Seleccionado el Panel 3."));
}
/**
*
* @author R
*
*/
class ControlCardLayout implements ActionListener{
CardLayoutEjemplo ejemplo;
public ControlCardLayout( CardLayoutEjemplo ejemplo){
ejemplo = ejemplo ;
}
public void actionPerformed (ActionEvent evento){
if (evento.getSource() == ejemplo.jcb) {
if (ejemplo.jcb.getSelectedIndex()==0){
ejemplo.cardLayout.show(ejemplo.pnlInf, "panel1");
}
if (ejemplo.jcb.getSelectedIndex()==1){
ejemplo.cardLayout.show(ejemplo.pnlInf, "panel2");
}
if (ejemplo.jcb.getSelectedIndex()==2){
ejemplo.cardLayout.show(ejemplo.pnlInf, "panel3");
}
}
}
}
}

View File

@@ -0,0 +1,73 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class EjemploGroupLayoutPane extends JPanel {
JLabel label = new JLabel("Find What:");;
JTextField textField = new JTextField();
JCheckBox caseCheckBox = new JCheckBox("Match Case");
JCheckBox wrapCheckBox = new JCheckBox("Wrap Around");
JCheckBox wholeCheckBox = new JCheckBox("Whole Words");
JCheckBox backCheckBox = new JCheckBox("Search Backwards");
JButton findButton = new JButton("Find");
JButton cancelButton = new JButton("Cancel");
/**
*
*/
public EjemploGroupLayoutPane () {
// remove redundant default border of check boxes - they would hinder
// correct spacing and aligning (maybe not needed on some look and feels)
caseCheckBox.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
wrapCheckBox.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
wholeCheckBox.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
backCheckBox.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(label)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(textField)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(caseCheckBox)
.addComponent(wholeCheckBox))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(wrapCheckBox)
.addComponent(backCheckBox))))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(findButton)
.addComponent(cancelButton))
);
layout.linkSize(SwingConstants.HORIZONTAL, findButton, cancelButton);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(label)
.addComponent(textField)
.addComponent(findButton))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(caseCheckBox)
.addComponent(wrapCheckBox))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(wholeCheckBox)
.addComponent(backCheckBox)))
.addComponent(cancelButton))
);
}
}

View File

@@ -0,0 +1,14 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JPanel;
public class EjemploSpringLayout extends JPanel {
/**
*
*/
public EjemploSpringLayout () {
}
}

View File

@@ -0,0 +1,137 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import tutorialJava.capitulo9_AWT_SWING.utils.CacheImagenes;
public class EjemplosJTabbedPane {
/**
*
* @return
*/
public static JTabbedPane getPanelesTabulados () {
JTabbedPane tabPanel = new JTabbedPane();
ImageIcon icono = CacheImagenes.getCacheImagenes().getIcono("duke1-32x32.png");
tabPanel.addTab("01 FlowLayout", icono, getTabFlowLayout(false), "Ejemplo de FlowLayout");
tabPanel.addTab("02 FlowLayout componentes", icono, getTabFlowLayout(true), "Ejemplo de FlowLayout");
tabPanel.addTab("03 BorderLayout", icono, getTabBorderLayout(false), "Ejemplo de BorderLayout");
tabPanel.addTab("04 BorderLayout componentes", icono, getTabBorderLayout(true), "Ejemplo de BorderLayout");
tabPanel.addTab("05 BoxLayout vertical", icono, getTabBoxLayout(false, true), "Ejemplo de BoxLayout Vertical");
tabPanel.addTab("06 BoxLayout vertical componentes", icono, getTabBoxLayout(true, true), "Ejemplo de BoxLayout Vertical");
tabPanel.addTab("07 BoxLayout horizontal", icono, getTabBoxLayout(false, false), "Ejemplo de BoxLayout Horizontal");
tabPanel.addTab("08 BoxLayout horizontal componentes", icono, getTabBoxLayout(true, false), "Ejemplo de BoxLayout Horizontal");
tabPanel.addTab("09 GridLayout", icono, getTabGridLayout(false), "Ejemplo de GridLayout");
tabPanel.addTab("10 GridLayout componentes", icono, getTabGridLayout(true), "Ejemplo de GridLayout");
tabPanel.addTab("11 GridBagLayout", icono, GridBagLayoutFactory.instance(false), "Ejemplo de GridBagLayout");
tabPanel.addTab("12 GridBagLayout componentes", icono, GridBagLayoutFactory.instance(true), "Ejemplo de GridBagLayout");
tabPanel.addTab("13 CardLayout", icono, new CardLayoutEjemplo(), "Ejemplo de CardLayout");
tabPanel.addTab("14 GroupLayout", icono, new EjemploGroupLayoutPane(), "Ejemplo de GroupLayout");
tabPanel.setSelectedIndex(0);
return tabPanel;
}
/**
*
* @param incluirComponentes
* @return
*/
private static JPanel getTabFlowLayout (boolean incluirComponentes) {
JPanel pnl = new JPanel();
for (int i = 0; i < 10; i++) {
pnl.add((incluirComponentes)? JComponentFactory.getJComponentAzar() : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), pnl);
}
return pnl;
}
/**
*
* @param incluirComponentes
* @return
*/
private static JPanel getTabBorderLayout (boolean incluirComponentes) {
JPanel pnl = new JPanel();
pnl.setLayout(new BorderLayout());
pnl.add((incluirComponentes)? JComponentFactory.getJComponentAzar() : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), BorderLayout.NORTH);
pnl.add((incluirComponentes)? JComponentFactory.getJComponentAzar() : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), BorderLayout.SOUTH);
pnl.add((incluirComponentes)? JComponentFactory.getJComponentAzar() : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), BorderLayout.CENTER);
pnl.add((incluirComponentes)? JComponentFactory.getJComponentAzar() : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), BorderLayout.WEST);
pnl.add((incluirComponentes)? JComponentFactory.getJComponentAzar() : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), BorderLayout.EAST);
return pnl;
}
/**
*
* @param incluirComponentes
* @return
*/
private static JPanel getTabBoxLayout (boolean incluirComponentes, boolean vertical) {
JPanel pnl = new JPanel();
pnl.setLayout(new BoxLayout(pnl, (vertical)? BoxLayout.Y_AXIS : BoxLayout.X_AXIS));
for (int i = 0; i < 10; i++) {
pnl.add((incluirComponentes)? JComponentFactory.getJComponentAzar() : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), pnl);
}
return pnl;
}
/**
*
* @param incluirComponentes
* @return
*/
private static JPanel getTabGridLayout (boolean incluirComponentes) {
JPanel jpn = new JPanel();
jpn.setLayout(new GridLayout(3, 2));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JLABEL) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JTEXTFIELD) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JLABEL) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JCHECKBOX) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JLABEL) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JTEXTAREA) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
return jpn;
}
/**
*
* @param incluirComponentes
* @return
*/
private static JPanel getTabFormLayout (boolean incluirComponentes) {
JPanel jpn = new JPanel();
jpn.setLayout(new GridLayout(3, 2));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JLABEL) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JTEXTFIELD) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JLABEL) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JCHECKBOX) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JLABEL) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JTEXTAREA) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL));
return jpn;
}
}

View File

@@ -0,0 +1,73 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JPanel;
public class GridBagLayoutFactory {
/**
*
* @param incluirComponentes
* @return
*/
public static JPanel instance (boolean incluirComponentes) {
JPanel jpn = new JPanel();
jpn.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.weightx = 1;
c.insets = new Insets(5, 5, 5, 5);
jpn.add(
(incluirComponentes)?
JComponentFactory.instanceJComponent(JComponentFactory.JLABEL) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL),
c);
c.gridx = 1;
// c.gridy = 0;
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JTEXTFIELD) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), c);
// Segunda fila
//c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JBUTTON) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), c);
// Tercera fila
c.gridx = 0;
c.gridy = 2;
//c.gridwidth = 2;
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JBUTTON) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), c);
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 3;
//c.gridwidth = 1;
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JBUTTON) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), c);
//c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 4;
c.anchor = GridBagConstraints.SOUTHWEST;
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JBUTTON) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), c);
/*
c.fill = GridBagConstraints.VERTICAL;
c.gridx = 1;
c.gridy = 3;
c.gridheight = 2;
c.weighty = 1;
c.anchor = GridBagConstraints.CENTER;
jpn.add((incluirComponentes)? JComponentFactory.instanceJComponent(JComponentFactory.JBUTTON) : JComponentFactory.instanceJComponent(JComponentFactory.JPANEL), c);
*/
return jpn;
}
}

View File

@@ -0,0 +1,27 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JButton;
import tutorialJava.capitulo9_AWT_SWING.utils.CacheImagenes;
public class JButtonFactory {
/**
*
* @return
*/
public static JButton instance () {
return instance ("JButton");
}
/**
*
* @param texto
* @return
*/
public static JButton instance (String texto) {
JButton jbt = new JButton(texto);
jbt.setIcon(CacheImagenes.getCacheImagenes().getIcono("duke1-32x32.png"));
return jbt;
}
}

View File

@@ -0,0 +1,27 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
public class JCheckBoxFactory {
/**
*
* @return
*/
public static JCheckBox instance () {
return instance ("JCheckBox");
}
/**
*
* @param texto
* @return
*/
public static JCheckBox instance (String texto) {
JCheckBox jl = new JCheckBox(texto);
return jl;
}
}

View File

@@ -0,0 +1,33 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
public class JComboBoxFactory {
/**
*
* @return
*/
public static JComboBox instance () {
String opciones[] = new String[10];
for (int i = 0; i < opciones.length; i++) {
opciones[i] = "JComboBox Option " + i;
}
return instance (opciones);
}
/**
*
* @param texto
* @return
*/
public static JComboBox instance (String opciones[]) {
JComboBox jcb = new JComboBox(opciones);
jcb.setSelectedIndex(0);
return jcb;
}
}

View File

@@ -0,0 +1,78 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JComponent;
import tutorialJava.Utils;
public class JComponentFactory {
public static int JPANEL = 0;
public static int JTEXTFIELD = 1;
public static int JBUTTON = 2;
public static int JLABEL = 3;
public static int JCHECKBOX = 4;
public static int JCOMBOBOX = 5;
public static int JLIST = 6;
public static int JRADIOBUTTON = 7;
public static int JTEXTAREA = 8;
public static int JSLIDER = 9;
public static int JPASSWORD = 10;
public static int JPROGRESSBAR = 11;
public static JComponent getJComponentAzar () {
return instanceJComponent (Utils.obtenerNumeroAzar(1, 11));
}
/**
*
* @param id
* @return
*/
public static JComponent instanceJComponent (int id) {
if (id == JPANEL) {
return JPanelFactory.instanceJPanelColorAzar();
}
if (id == JTEXTFIELD) {
return JTextFieldFactory.instance(10);
}
if (id == JBUTTON) {
return JButtonFactory.instance();
}
if (id == JLABEL) {
return JLabelFactory.instance();
}
if (id == JCHECKBOX) {
return JCheckBoxFactory.instance();
}
if (id == JCOMBOBOX) {
return JComboBoxFactory.instance();
}
if (id == JLIST) {
return JListFactory.instance();
}
if (id == JRADIOBUTTON) {
return JRadioButtonFactory.instance();
}
if (id == JTEXTAREA) {
return JTextAreaFactory.instance();
}
if (id == JSLIDER) {
return JSliderFactory.instance();
}
if (id == JPASSWORD) {
return JPasswordFieldFactory.instance();
}
if (id == JPROGRESSBAR) {
return JProgressBarFactory.instance();
}
return null;
}
}

View File

@@ -0,0 +1,24 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JButton;
import javax.swing.JLabel;
public class JLabelFactory {
public static JLabel instance () {
return instance ("JLabel");
}
/**
*
* @param texto
* @return
*/
public static JLabel instance (String texto) {
JLabel jl = new JLabel(texto);
return jl;
}
}

View File

@@ -0,0 +1,38 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
public class JListFactory {
/**
*
* @return
*/
public static JList instance () {
String opciones[] = new String[10];
for (int i = 0; i < opciones.length; i++) {
opciones[i] = "JList Option " + i;
}
return instance (opciones);
}
/**
*
* @param texto
* @return
*/
public static JList instance (String opciones[]) {
JList jl = new JList(opciones);
jl.setSelectedIndex(0);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jl.setLayoutOrientation(JList.VERTICAL);
jl.setVisibleRowCount(5);
return jl;
}
}

View File

@@ -0,0 +1,38 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import java.awt.Color;
import javax.swing.JPanel;
import tutorialJava.Utils;
public class JPanelFactory {
private static char digitosHexadecimales[] = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
*
* @return
*/
public static JPanel instanceJPanelColorAzar () {
JPanel pnl = new JPanel();
pnl.setBackground(Color.decode(getColorAzar()));
return pnl;
}
/**
*
* @return
*/
private static String getColorAzar () {
StringBuffer sb = new StringBuffer ("#");
for (int i = 0; i < 6; i++) {
sb.append(digitosHexadecimales[Utils.obtenerNumeroAzar(0, digitosHexadecimales.length-1)]);
}
return sb.toString();
}
}

View File

@@ -0,0 +1,44 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JPasswordField;
public class JPasswordFieldFactory {
/**
*
* @return
*/
public static JPasswordField instance () {
return instance (1);
}
/**
*
* @param longitud
* @return
*/
public static JPasswordField instance (int longitud) {
return instance ("JPasswordField", longitud);
}
/**
*
* @param texto
* @return
*/
public static JPasswordField instance (String texto) {
return instance (texto, 10);
}
/**
*
* @param texto
* @param longitud
* @return
*/
public static JPasswordField instance (String texto, int longitud) {
JPasswordField jtf = new JPasswordField (texto, longitud);
return jtf;
}
}

View File

@@ -0,0 +1,31 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JProgressBar;
public class JProgressBarFactory {
/**
*
* @return
*/
public static JProgressBar instance () {
return instance (0, 1432, 568);
}
/**
*
* @param min
* @param max
* @param valor
* @return
*/
public static JProgressBar instance (int min, int max, int valor) {
JProgressBar jpb = new JProgressBar (min, max);
jpb.setValue(valor);
jpb.setStringPainted(true);
return jpb;
}
}

View File

@@ -0,0 +1,50 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class JRadioButtonFactory {
/**
*
* @return
*/
public static JPanel instance () {
String opciones[] = new String[5];
for (int i = 0; i < opciones.length; i++) {
opciones[i] = "JRadioButton Option " + i;
}
return instance (opciones);
}
/**
*
* @param opciones
* @return
*/
public static JPanel instance (String opciones[]) {
JPanel jpn = new JPanel();
jpn.setLayout(new BoxLayout(jpn, BoxLayout.Y_AXIS));
ButtonGroup grupoOpciones = new ButtonGroup();
for (int i = 0; i < opciones.length; i++) {
JRadioButton jrb = new JRadioButton (opciones[i]);
jrb.setSelected(true);
grupoOpciones.add(jrb);
jpn.add(jrb);
}
return jpn;
}
}

View File

@@ -0,0 +1,33 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JSlider;
import tutorialJava.Utils;
public class JSliderFactory {
static final int MIN = 0;
static final int MAX = 30;
static final int INIT = 15;
public static JSlider instance() {
return instance ((Utils.obtenerNumeroAzar(0, 1) == 0) ? JSlider.HORIZONTAL : JSlider.VERTICAL, MIN, MAX, INIT);
}
/**
*
* @param texto
* @return
*/
public static JSlider instance (int tipo, int min, int max, int init) {
JSlider js = new JSlider (tipo, min, max, init);
js.setMajorTickSpacing(10);
js.setMinorTickSpacing(1);
js.setPaintTicks(true);
js.setPaintLabels(true);
return js;
}
}

View File

@@ -0,0 +1,29 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class JTextAreaFactory {
public static JTextArea instance() {
return instance ("JTextArea");
}
/**
*
* @param texto
* @return
*/
public static JTextArea instance (String texto) {
JTextArea jta = new JTextArea (5, 20);
jta.setText(texto);
jta.setLineWrap(true);
return jta;
}
}

View File

@@ -0,0 +1,44 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import javax.swing.JTextField;
public class JTextFieldFactory {
/**
*
* @return
*/
public static JTextField instance () {
return instance (1);
}
/**
*
* @param longitud
* @return
*/
public static JTextField instance (int longitud) {
return instance ("JTextField", longitud);
}
/**
*
* @param texto
* @return
*/
public static JTextField instance (String texto) {
return instance (texto, 10);
}
/**
*
* @param texto
* @param longitud
* @return
*/
public static JTextField instance (String texto, int longitud) {
JTextField jtf = new JTextField (texto, longitud);
return jtf;
}
}

View File

@@ -0,0 +1,10 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
public class Main {
public static void main(String[] args) {
VentanaPrincipal ventanaPrincipal = new VentanaPrincipal ();
ventanaPrincipal.setVisible(true);
}
}

View File

@@ -0,0 +1,74 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import tutorialJava.capitulo9_AWT_SWING.utils.Apariencia;
import tutorialJava.capitulo9_AWT_SWING.utils.CacheImagenes;
public class VentanaPrincipal extends JFrame {
public static int ANCHO = 800;
public static int ALTO = 600;
public static String TITULO_APLICACION = "T<EFBFBD>tulo de la aplicaci<63>n";
private CacheImagenes cacheImagenes;
public static BufferedImage iconoApp;
// Establecer la apariencia t<>pica de Windows
static {
Apariencia.setAparienciasOrdenadas(Apariencia.aparienciasOrdenadas);
}
public VentanaPrincipal () {
super (TITULO_APLICACION);
cacheImagenes = new CacheImagenes();
iconoApp = cacheImagenes.getImagen("nave.gif");
setIconImage(iconoApp);
// Tama<6D>o por defecto, basado en los valores est<73>ticos de esta misma clase
setDimensionesBasicas();
// Construcci<63>n elementos b<>sicos sobre el ContentPanel
this.setContentPane(EjemplosJTabbedPane.getPanelesTabulados());
}
/**
*
*/
private void setDimensionesBasicas () {
this.setExtendedState(JFrame.NORMAL);
this.setBounds(0, 0, ANCHO, ALTO);
//this.setMinimumSize(new Dimension(ANCHO, ALTO));
}
/**
*
*/
private void agregarGestionCierreAplicacion () {
// Configuraci<63>n del evento de cerrado
// Para m<>s informaci<63>n debes estudiar Javadoc WindowListener y WindowAdapter
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
String posiblesRespuestas[] = {"S<EFBFBD>","No"};
// En esta opci<63>n se utiliza un showOptionDialog en el que personalizo el icono mostrado
int opcionElegida = JOptionPane.showOptionDialog(null, "<EFBFBD>Realmente desea cerrar la aplicaci<63>n?", TITULO_APLICACION,
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, cacheImagenes.getIcono("confirm.png"), posiblesRespuestas, posiblesRespuestas[1]);
if(opcionElegida == 0) {
System.exit(0);
}
}
});
}
}

View File

@@ -0,0 +1,68 @@
package tutorialJava.capitulo9_AWT_SWING.v02_LayoutsYPrimerosJComponents.ejemplo01BorderLayout;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JSlider;
import tutorialJava.capitulo9_AWT_SWING.utils.Apariencia;
public class VentanaPrincipal extends JFrame {
static {
try {
Apariencia.setApariencia(Apariencia.WINDOWS);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
public VentanaPrincipal() {
this.setBounds(0, 0, 800, 600);
this.setContentPane(getPanelPrincipal());
}
/**
*
* @return
*/
private JPanel getPanelPrincipal() {
JPanel pnl = new JPanel();
pnl.setLayout(new BorderLayout());
JProgressBar jpb = new JProgressBar (0, 100);
jpb.setValue(50);
jpb.setStringPainted(true);
pnl.add(jpb, BorderLayout.NORTH);
JButton jbtBoton = new JButton("Es un botón");
pnl.add(jbtBoton, BorderLayout.SOUTH);
JSlider js = new JSlider (JSlider.VERTICAL, 0, 100, 50);
js.setMajorTickSpacing(10);
js.setMinorTickSpacing(1);
js.setPaintTicks(true);
js.setPaintLabels(true);
pnl.add(js, BorderLayout.WEST);
return pnl;
}
public static void main(String[] args) {
VentanaPrincipal vp = new VentanaPrincipal();
vp.setVisible(true);
}
}

View File

@@ -0,0 +1,53 @@
package tutorialJava.capitulo9_AWT_SWING.v03_JComponentsAvanzados.JPanelIntoJDialog;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
public class PanelAInsertarEnJDialog extends JPanel {
/**
* Create the panel.
*/
public PanelAInsertarEnJDialog() {
setLayout(new BorderLayout(0, 0));
JToolBar toolBar = new JToolBar();
add(toolBar, BorderLayout.NORTH);
JButton btnNewButton = new JButton("");
btnNewButton.setIcon(new ImageIcon(PanelAInsertarEnJDialog.class.getResource("/tutorialJava/capitulo8_AWT_SWING/res/gotostart.png")));
toolBar.add(btnNewButton);
JButton btnNewButton_1 = new JButton("");
btnNewButton_1.setIcon(new ImageIcon(PanelAInsertarEnJDialog.class.getResource("/tutorialJava/capitulo8_AWT_SWING/res/previous.png")));
toolBar.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("");
btnNewButton_2.setIcon(new ImageIcon(PanelAInsertarEnJDialog.class.getResource("/tutorialJava/capitulo8_AWT_SWING/res/next.png")));
toolBar.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("");
btnNewButton_3.setIcon(new ImageIcon(PanelAInsertarEnJDialog.class.getResource("/tutorialJava/capitulo8_AWT_SWING/res/gotoend.png")));
toolBar.add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("");
btnNewButton_4.setIcon(new ImageIcon(PanelAInsertarEnJDialog.class.getResource("/tutorialJava/capitulo8_AWT_SWING/res/nuevo.png")));
toolBar.add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("");
btnNewButton_5.setIcon(new ImageIcon(PanelAInsertarEnJDialog.class.getResource("/tutorialJava/capitulo8_AWT_SWING/res/guardar.png")));
toolBar.add(btnNewButton_5);
JButton btnNewButton_6 = new JButton("");
btnNewButton_6.setIcon(new ImageIcon(PanelAInsertarEnJDialog.class.getResource("/tutorialJava/capitulo8_AWT_SWING/res/eliminar.png")));
toolBar.add(btnNewButton_6);
JPanel panelPrincipal = new JPanel();
add(panelPrincipal, BorderLayout.CENTER);
}
}

View File

@@ -0,0 +1,55 @@
package tutorialJava.capitulo9_AWT_SWING.v03_JComponentsAvanzados.JPanelIntoJDialog;
import javax.swing.JPanel;
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 PanelConBoton extends JPanel {
/**
* Create the panel.
*/
public PanelConBoton() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JButton btnButton = new JButton("Abrir JPanel en JDialog");
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog dialogo = new JDialog();
// El usuario no puede redimensionar el diálogo
dialogo.setResizable(true);
// título del díalogo
dialogo.setTitle("Título");
// Introducimos el panel creado sobre el diálogo
dialogo.setContentPane(new PanelAInsertarEnJDialog());
// 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);
}
});
GridBagConstraints gbc_btnButton = new GridBagConstraints();
gbc_btnButton.gridx = 0;
gbc_btnButton.gridy = 0;
add(btnButton, gbc_btnButton);
}
}

View File

@@ -0,0 +1,21 @@
package tutorialJava.capitulo9_AWT_SWING.v03_JComponentsAvanzados;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import tutorialJava.capitulo9_AWT_SWING.utils.CacheImagenes;
public class JScroolPaneConImagen extends JScrollPane {
String imagen = null;
/**
* @param imagen
*/
public JScroolPaneConImagen(String imagen) {
super(new JLabel(CacheImagenes.getCacheImagenes().getIcono(imagen)));
this.imagen = imagen;
}
}

View File

@@ -0,0 +1,123 @@
package tutorialJava.capitulo9_AWT_SWING.v03_JComponentsAvanzados;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.KeyStroke;
import tutorialJava.capitulo9_AWT_SWING.utils.CacheImagenes;
public class Menu extends JMenuBar {
/**
*
*/
public Menu () {
// Menú Archivo de la aplicación
JMenu menuArchivo = new JMenu("Archivo");
menuArchivo.add(crearNuevoMenuItem("Abrir", "ruedadentada.png", KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
JMenu menuExportar = new JMenu("Exportar");
menuExportar.add(crearNuevoMenuItem("Como Word", "ruedadentada.png", KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
menuExportar.add(crearNuevoMenuItem("Como Excel", "ruedadentada.png", KeyStroke.getKeyStroke(KeyEvent.VK_E, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
menuArchivo.add(menuExportar);
menuArchivo.add(crearNuevoMenuItem("Cerrar", "conectado.png", KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
menuArchivo.addSeparator();
menuArchivo.add(crearNuevoMenuItem("Salir", "exit.png", KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
this.add(menuArchivo);
// Men<65> editar
JMenu menuEditar = new JMenu("Editar");
menuEditar.add(crearNuevoMenuItem("Cortar", "next.png", KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
menuEditar.add(crearNuevoMenuItem("Copiar", "previous.png", KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
menuEditar.addSeparator();
menuEditar.add(crearNuevoMenuItem("Pegar", "eliminar.png", KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())));
this.add(menuEditar);
// Men<65> ejemplo checkbox y radio
JMenu menuCheckBoxYRadio = new JMenu("CheckBoxYRadio");
menuCheckBoxYRadio.add(crearNuevoCheckBoxMenuItem("Ejemplo JCheckBoxMenuItem", "valign16.png"));
menuCheckBoxYRadio.addSeparator();
// Ejemplo del JRadioButtonMenuItem
ButtonGroup buttonGroup = new ButtonGroup();
menuCheckBoxYRadio.add(crearNuevoRadioButtonMenuItem("Radio Button - Opción 1", "previous.png", buttonGroup));
menuCheckBoxYRadio.add(crearNuevoRadioButtonMenuItem("Radio Button - Opción 2", "previous.png", buttonGroup));
menuCheckBoxYRadio.add(crearNuevoRadioButtonMenuItem("Radio Button - Opción 3", "previous.png", buttonGroup));
this.add(menuCheckBoxYRadio);
}
/**
* Menú Item para salir de la aplicación
* @return
*/
private JMenuItem crearNuevoMenuItem (String titulo, String nombreIcono, KeyStroke atajoTeclado) {
JMenuItem item = new JMenuItem(titulo);
item.setIcon(CacheImagenes.getCacheImagenes().getIcono(nombreIcono));
item.setAccelerator(atajoTeclado);
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Han hecho clic en: " + titulo);
}
});
return item;
}
/**
*
* @param titulo
* @param nombreIcono
* @return
*/
private JMenuItem crearNuevoCheckBoxMenuItem (String titulo, String nombreIcono) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem(titulo);
item.setIcon(CacheImagenes.getCacheImagenes().getIcono(nombreIcono));
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Han hecho clic en el JCheckBox: " + titulo + " - Seleccionado: " + item.isSelected());
}
});
return item;
}
/**
*
* @param titulo
* @param nombreIcono
* @return
*/
private JMenuItem crearNuevoRadioButtonMenuItem (String titulo, String nombreIcono, ButtonGroup buttonGroup) {
JRadioButtonMenuItem item = new JRadioButtonMenuItem(titulo);
item.setIcon(CacheImagenes.getCacheImagenes().getIcono(nombreIcono));
item.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Han hecho clic en el JRadioButton: " + titulo + " - Seleccionado: " + item.isSelected());
}
});
buttonGroup.add(item);
return item;
}
}

View File

@@ -0,0 +1,76 @@
package tutorialJava.capitulo9_AWT_SWING.v03_JComponentsAvanzados;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class PanelJColorChooser extends JPanel {
JTextField jtfColor = new JTextField();
JButton jbtSeleccionar = new JButton ("Seleccionar color");
JPanel jpPanelParaColorear = new JPanel();
JColorChooser jColorChooser;
/**
*
*/
public PanelJColorChooser() {
super();
this.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 5, 5);
// Incluyo el JTextField del nombre del fichero
constraints.gridx = 0;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weightx = 1;
this.add(jtfColor, constraints);
// Incluyo el botón que abrirá el dialogo del JFileChooser
constraints.gridx = 1;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weightx = 0.25;
this.add(jbtSeleccionar, constraints);
// Incluyo el área de texto que mostrará el fichero
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.fill = GridBagConstraints.BOTH;
constraints.weighty = 1;
this.add(this.jpPanelParaColorear, constraints);
// Funcionalidad al botón
jbtSeleccionar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
seleccionaColor();
}
});
}
/**
*
*/
private void seleccionaColor () {
Color color = jColorChooser.showDialog(null, "Seleccione un Color", Color.gray);
// Si el usuario pulsa sobre aceptar, el color elegido no será nulo
if (color != null) {
String strColor = "#"+Integer.toHexString(color.getRGB()).substring(2);
this.jtfColor.setText(strColor);
this.jpPanelParaColorear.setBackground(color);
}
}
}

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