diff --git a/.gitignore b/.gitignore index fbd9690..b40b47d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -Ejercicio1/src/main/java/models/Credenciales.java +*/src/main/java/models/Credenciales.java diff --git a/.project b/.project index bd32f58..fa49362 100644 --- a/.project +++ b/.project @@ -14,4 +14,15 @@ org.eclipse.jdt.core.javanature + + + 1681308613588 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + diff --git a/Ejercicio1/.classpath b/Ejercicio1/.classpath index 5e8a55f..f0257c5 100644 --- a/Ejercicio1/.classpath +++ b/Ejercicio1/.classpath @@ -23,5 +23,22 @@ + + + + + + + + + + + + + + + + + diff --git a/Ejercicio1/.project b/Ejercicio1/.project index 680b8a0..5e526a0 100644 --- a/Ejercicio1/.project +++ b/Ejercicio1/.project @@ -20,4 +20,15 @@ org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature + + + 1681308613605 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + diff --git a/Ejercicio1/.settings/org.eclipse.jdt.apt.core.prefs b/Ejercicio1/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 0000000..d4313d4 --- /dev/null +++ b/Ejercicio1/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/Ejercicio1/.settings/org.eclipse.jdt.core.prefs b/Ejercicio1/.settings/org.eclipse.jdt.core.prefs index dfefb9a..70d61cf 100644 --- a/Ejercicio1/.settings/org.eclipse.jdt.core.prefs +++ b/Ejercicio1/.settings/org.eclipse.jdt.core.prefs @@ -106,5 +106,6 @@ org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.processAnnotations=disabled org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=1.8 diff --git a/Ejercicio1/src/main/java/app1Main/App.java b/Ejercicio1/src/main/java/app1Main/App.java index c900f43..30f5a4e 100644 --- a/Ejercicio1/src/main/java/app1Main/App.java +++ b/Ejercicio1/src/main/java/app1Main/App.java @@ -2,9 +2,7 @@ import javax.swing.*; import controller.*; -import views.Cliente_Index; -import views.Cliente_InsertView; -import views.Cliente_ListView; +import models.DataBase; /** * @author Javier @@ -25,14 +23,7 @@ public static void main( String[] args ) { catch (IllegalAccessException e) { } -// Cliente_InsertView insertView = new Cliente_InsertView(); -// Cliente_InsertController controllerInsert = new Cliente_InsertController(insertView); -// controllerInsert.initVista(); -// Cliente_ListView listView = new Cliente_ListView(); -// Cliente_ListController controller = new Cliente_ListController(listView); -// controller.initVista(); - Cliente_Index insertIndex = new Cliente_Index(); - Cliente_IndexController controller = new Cliente_IndexController(insertIndex); - controller.initVista(); + DataBase.init(); + new ListController(); } } diff --git a/Ejercicio1/src/main/java/controller/Cliente_InsertController.java b/Ejercicio1/src/main/java/controller/Cliente_InsertController.java deleted file mode 100644 index 028aa40..0000000 --- a/Ejercicio1/src/main/java/controller/Cliente_InsertController.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * - */ -package controller; - -import java.awt.event.*; -import java.sql.Date; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; - -import javax.swing.*; - -import models.*; -import views.*; - -/** - * @author Javier - * - */ -public class Cliente_InsertController implements ActionListener { - - private Cliente cliente; - private Cliente_InsertView insert; - - - public Cliente_InsertController(Cliente_InsertView insert) { - this.insert = insert; - this.insert.crear.addActionListener(this); - } - - @Override - public void actionPerformed(ActionEvent e) { - - String nombre = insert.nombre.getText(); - String apellidos = insert.apellidos.getText(); - String direccion = insert.direccion.getText(); - int dni = Integer.parseInt(insert.dni.getText()); - - String fechaTexto = insert.fecha.getText(); // Obtener el texto del campo de fecha - DateTimeFormatter formatoFecha = DateTimeFormatter.ofPattern("yyyy-MM-dd");//establecer el formato - - try { - LocalDate fechaLocal = LocalDate.parse(fechaTexto, formatoFecha); // Analizar el texto de la fecha y crear un objeto LocalDate a partir de ella - java.sql.Date fecha = java.sql.Date.valueOf(fechaLocal); // Convertir el objeto LocalDate a un objeto java.sql.Date - cliente = new Cliente(0, nombre, apellidos, direccion, dni, fecha); - } catch (DateTimeParseException ex) { - ex.printStackTrace(); - } - - - cliente.insert(); - - JOptionPane.showMessageDialog(insert, "Cliente creado correctamente."); - insert.dispose(); - } - - public void initVista() { - - insert.setTitle("Nuevo cliente"); - insert.setBounds(300, 300, 354, 351); - insert.setLocationRelativeTo(null); - insert.setVisible(true); - } -} diff --git a/Ejercicio1/src/main/java/controller/Cliente_ListController.java b/Ejercicio1/src/main/java/controller/Cliente_ListController.java deleted file mode 100644 index b736437..0000000 --- a/Ejercicio1/src/main/java/controller/Cliente_ListController.java +++ /dev/null @@ -1,58 +0,0 @@ -package controller; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; -import javax.swing.JFrame; -import models.Cliente; -import views.Cliente_InsertView; -import views.Cliente_ListView; -import javax.swing.table.DefaultTableModel; - - -public class Cliente_ListController implements ActionListener { - - private Cliente cliente; - private Cliente_ListView list; - - public Cliente_ListController(Cliente_ListView list) { - this.cliente = new Cliente(); - this.list = list; - this.list.add.addActionListener(this); - } - - public void initVista() { - list.setTitle("Lista de clientes"); - list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - list.setBounds(300, 300, 450, 351); - list.setLocationRelativeTo(null); - list.setVisible(true); - - list.table.setModel(list()); - } - - public DefaultTableModel list() { - List clientes = cliente.select(); - DefaultTableModel model = new DefaultTableModel( - new String[]{"ID", "Nombre", "Apellido", "Dirección", "DNI", "Fecha"}, 0); - - for (Cliente c : clientes) { - Object[] fila = new Object[6]; - fila[0] = c.getId(); - fila[1] = c.getNombre(); - fila[2] = c.getApellido(); - fila[3] = c.getDireccion(); - fila[4] = c.getDni(); - fila[5] = c.getFecha(); - model.addRow(fila); - } - return model; - } - - @Override - public void actionPerformed(ActionEvent e) { - Cliente_InsertView insertView = new Cliente_InsertView(); - Cliente_InsertController controller = new Cliente_InsertController(insertView); - controller.initVista(); - } -} diff --git a/Ejercicio1/src/main/java/controller/EditCliente_Controller.java b/Ejercicio1/src/main/java/controller/EditCliente_Controller.java new file mode 100644 index 0000000..951e78e --- /dev/null +++ b/Ejercicio1/src/main/java/controller/EditCliente_Controller.java @@ -0,0 +1,98 @@ +/** + * + */ +package controller; + +import java.awt.event.*; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import javax.swing.*; + +import models.*; +import views.*; + +/** + * @author Joan + * Esta clase añade (insert) o modifica (update) un elemento de la tabla cliente + * Si elementToUpdate==null, inserta un nuevo elemento + * Si no, modifica el elemento cuyos campos son elementToUpdate + */ +public class EditCliente_Controller implements ActionListener { + + private EditCliente_View view; + private ListController listController; + private String[] elementToUpdate = null; + + // insert cliente + public EditCliente_Controller(ListController listController) { + this.listController = listController; + initVista(); + view.setTitle("Nuevo cliente"); + view.tituloVentana.setText("NUEVO CLIENTE"); + view.button.setText("Añadir"); + } + + // update cliente + public EditCliente_Controller(ListController listController, String[] elementToUpdate) { + this.listController = listController; + this.elementToUpdate = elementToUpdate; + initVista(); + view.setTitle("Modificar cliente"); + view.tituloVentana.setText("MODIFICAR CLIENTE"); + view.button.setText("Modificar"); + + view.nombre.setText(elementToUpdate[1]); + view.apellidos.setText(elementToUpdate[2]); + view.direccion.setText(elementToUpdate[3]); + view.dni.setText(elementToUpdate[4]); + view.fecha.setText(elementToUpdate[5]); + } + + public void initVista() { + view = new EditCliente_View(); + view.button.addActionListener(this); + view.setBounds(300, 300, 354, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + String nombre = view.nombre.getText(); + String apellidos = view.apellidos.getText(); + String direccion = view.direccion.getText(); + int dni = 0; + java.sql.Date fecha = null; + + try { + dni = Integer.parseInt(view.dni.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El DNI debe ser un número entero"); + return; + } + try { + String fechaTexto = view.fecha.getText(); // Obtener el texto del campo de fecha + DateTimeFormatter formatoFecha = DateTimeFormatter.ofPattern("yyyy-MM-dd");//establecer el formato + LocalDate fechaLocal = LocalDate.parse(fechaTexto, formatoFecha); // Analizar el texto de la fecha y crear un objeto LocalDate a partir de ella + fecha = java.sql.Date.valueOf(fechaLocal); // Convertir el objeto LocalDate a un objeto java.sql.Date + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El formato de la fecha es incorrecto (formato deseado: aaaa-mm-dd)"); + return; + } + + String[] columns = {"Nombre", "Apellido", "Direccion", "DNI", "Fecha"}; + String[] values = {nombre,apellidos,direccion,Integer.toString(dni),fecha.toString()}; + if (elementToUpdate == null) { + DataBase.cliente.insert(columns, values); + } + else { + DataBase.cliente.update(elementToUpdate, columns, values); + } + listController.refreshList(); + view.dispose(); + + } + + +} diff --git a/Ejercicio1/src/main/java/controller/Cliente_IndexController.java b/Ejercicio1/src/main/java/controller/IndexController.java similarity index 59% rename from Ejercicio1/src/main/java/controller/Cliente_IndexController.java rename to Ejercicio1/src/main/java/controller/IndexController.java index 95d020b..ea1f205 100644 --- a/Ejercicio1/src/main/java/controller/Cliente_IndexController.java +++ b/Ejercicio1/src/main/java/controller/IndexController.java @@ -3,26 +3,18 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.JButton; import javax.swing.JFrame; -import javax.swing.JPanel; import javax.swing.border.EmptyBorder; -import models.Cliente; -import views.Cliente_Index; -import views.Cliente_InsertView; -import views.Cliente_ListView; +import views.IndexView; -public class Cliente_IndexController implements ActionListener{ +public class IndexController implements ActionListener{ - private Cliente cliente; - private Cliente_Index indice; - private Cliente_InsertView insertView; + private IndexView indice; - public Cliente_IndexController(Cliente_Index indice) { - this.cliente = new Cliente(); + public IndexController(IndexView indice) { this.indice = indice; this.indice.nuevoCliente.addActionListener(this); this.indice.editarCliente.addActionListener(this); @@ -36,29 +28,20 @@ public void initVista() { indice.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); indice.setVisible(true); - - } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == indice.nuevoCliente) { // Crear y mostrar la vista de inserción de cliente - Cliente_InsertView insertView = new Cliente_InsertView(); - Cliente_InsertController insertController = new Cliente_InsertController(insertView); - insertController.initVista(); + //EditCliente_Controller insertController = new EditCliente_Controller(); + //insertController.initVista(); } else if (e.getSource() == indice.verCliente) { // Crear y mostrar la vista de visualización de clientes - Cliente_ListView listView = new Cliente_ListView(); - Cliente_ListController listController = new Cliente_ListController(listView); + ListController listController = new ListController(); listController.initVista(); } - - - - - } } diff --git a/Ejercicio1/src/main/java/controller/ListController.java b/Ejercicio1/src/main/java/controller/ListController.java new file mode 100644 index 0000000..8708abf --- /dev/null +++ b/Ejercicio1/src/main/java/controller/ListController.java @@ -0,0 +1,83 @@ +package controller; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import models.DataBase; +import views.ListView; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.table.DefaultTableModel; + + + +public class ListController implements ActionListener { + + private ListView view; + + public ListController() { + view = new ListView(); + view.insert.addActionListener(this); + view.delete.addActionListener(this); + view.update.addActionListener(this); + initVista(); + refreshList(); + } + + public void initVista() { + view.setTitle("Lista de clientes"); + view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + view.setBounds(300, 300, 450, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + public void refreshList() { + view.table.setModel(list()); + } + + private DefaultTableModel list() { + List rows = DataBase.cliente.select(); + DefaultTableModel model = new DefaultTableModel(DataBase.cliente.getAttributeNames(), 0); + for (String[] row : rows) { + model.addRow(row); + } + return model; + } + + private String[] getRowValues() { + int row = view.table.getSelectedRow(); + if (row == -1) { + JOptionPane.showMessageDialog(view, "Seleccione una fila"); + return null; + } + int n = view.table.getColumnCount(); + String[] values = new String[n]; + for (int i = 0; i < n; i++) { + values[i] = view.table.getValueAt(row, i).toString(); + } + return values; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.insert) { + new EditCliente_Controller(this); + } + else if (e.getSource() == view.delete) { + String[] row_values = getRowValues(); + if (row_values != null) { + if (0 == JOptionPane.showConfirmDialog(view, "¿Está seguro de que quiere eliminar este cliente?")) { + DataBase.cliente.delete(row_values); + refreshList(); + } + } + } + else if (e.getSource() == view.update) { + String[] row_values = getRowValues(); + if (row_values != null) { + new EditCliente_Controller(this, row_values); + } + } + } +} diff --git a/Ejercicio1/src/main/java/models/Attribute.java b/Ejercicio1/src/main/java/models/Attribute.java new file mode 100644 index 0000000..ed82e06 --- /dev/null +++ b/Ejercicio1/src/main/java/models/Attribute.java @@ -0,0 +1,31 @@ +package models; + +/** + * @author Joan + * esta clase representa el atributo de una tabla de una BD + */ +public class Attribute { + public String name; + public String type; + public String others = ""; + + // example: JEFE CHARVAR(30) NOT NULL REFERENCES EMPLEADO + // name="JEFE", type="CHARVAR", type_cardinality="(30)", + // others=["NOT", "NULL", "REFERENCES", "EMPLEADO"] + + + Attribute(String name, String type) { + this.name = name; + this.type = type; + } + Attribute(String name, String type, String others) { + this.name = name; + this.type = type; + this.others = others; + } + + @Override + public String toString() { + return name + " " + type + " " + others; + } +} diff --git a/Ejercicio1/src/main/java/models/Cliente.java b/Ejercicio1/src/main/java/models/Cliente.java index c8402a1..be06d27 100644 --- a/Ejercicio1/src/main/java/models/Cliente.java +++ b/Ejercicio1/src/main/java/models/Cliente.java @@ -21,7 +21,6 @@ public class Cliente { private int dni; private Date fecha; - private static final Connector CONNEXION = new Connector(); private static final String DBNAME = "servicios"; private static final String TBNAME = "clientes"; @@ -48,14 +47,14 @@ public Cliente(int id, String nombre, String apellido, String direccion, int dni * This method create de database if exists. */ public void createDatabase() { - CONNEXION.createDB(DBNAME); + Connector.createDB(DBNAME); } /** * This method create table "clientes". */ public void createTable() { - CONNEXION.createTable(DBNAME, TBNAME, + Connector.createTable(DBNAME, TBNAME, "id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY," + "nombre VARCHAR(250) NOT NULL," + "apellido VARCHAR(250) NOT NULL," @@ -68,7 +67,7 @@ public void createTable() { * This method insert data into database. */ public void insert() { - CONNEXION.insert(DBNAME, TBNAME, + Connector.insert(DBNAME, TBNAME, "nombre, apellido, direccion, dni, fecha", "'" + this.nombre + "', '" + this.apellido + "', '" + this.direccion + "', " + this.dni + ", '" + this.fecha + "'"); } @@ -77,7 +76,7 @@ public void insert() { * This method select data. */ public List select() { - ResultSet resultSet = CONNEXION.select(DBNAME,TBNAME); + ResultSet resultSet = Connector.select(DBNAME,TBNAME); List clientes = new ArrayList<>(); try { while (resultSet.next()) { diff --git a/Ejercicio1/src/main/java/models/Connector.java b/Ejercicio1/src/main/java/models/Connector.java index e8a4318..4430c8b 100644 --- a/Ejercicio1/src/main/java/models/Connector.java +++ b/Ejercicio1/src/main/java/models/Connector.java @@ -12,11 +12,9 @@ public class Connector { private static final String URL = Credenciales.URL; private static final String USER = Credenciales.USER; private static final String PASSWORD = Credenciales.PASSWORD; - private static Connection conexion = null; - // Create connection - public Connector() { + public static void openConnection() { try { Class.forName(DRIVER); conexion = DriverManager.getConnection(URL, USER, PASSWORD); @@ -26,9 +24,8 @@ public Connector() { System.out.println(ex); } } - - // Close connection - public void closeConnection() { + + public static void closeConnection() { try { conexion.close(); JOptionPane.showMessageDialog(null, "Se ha finalizado la conexion con el servidor"); @@ -38,20 +35,20 @@ public void closeConnection() { } // Create database - public void createDB(String dbName) { + public static void createDB(String dbName) { try { String query = " CREATE DATABASE IF NOT EXISTS " + dbName + " ;"; Statement st = conexion.createStatement(); System.out.println(query); st.executeUpdate(query); - System.out.println("Se ha creado la base de datos " + dbName + " correctamente"); + System.out.println("\tSe ha creado la base de datos " + dbName + " correctamente"); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); } } // Create table - public void createTable(String nombreBBDD, String nombreTabla, String tablaColum) { + public static void createTable(String nombreBBDD, String nombreTabla, String tablaColum) { try { String queryDb = "USE " + nombreBBDD + ";"; Statement stdb = conexion.createStatement(); @@ -62,15 +59,15 @@ public void createTable(String nombreBBDD, String nombreTabla, String tablaColum System.out.println(query); st.executeUpdate(query); - System.out.println("Se ha creado la tabla " + nombreTabla + " correctamente"); + System.out.println("\tSe ha creado la tabla " + nombreTabla + " correctamente"); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error creando la tabla " + nombreTabla); } } - // Insert table - public void insert(String dbName, String tableName, String columns, String values) { + // Insert row to table table + public static void insert(String dbName, String tableName, String columns, String values) { try { String queryDb = "USE " + dbName + ";"; Statement stdb = conexion.createStatement(); @@ -81,15 +78,16 @@ public void insert(String dbName, String tableName, String columns, String value System.out.println(query); st.executeUpdate(query); - System.out.println("Datos insertados correctamente en la tabla " + tableName); + System.out.println("\tDatos insertados correctamente en la tabla " + tableName); } catch (SQLException ex) { - Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); - JOptionPane.showMessageDialog(null, "Error insertando datos en la tabla " + tableName); + //Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error insertando datos en la tabla"); } } - // Select - public ResultSet select(String db, String table_name) { + // Select all rows from table + public static ResultSet select(String db, String table_name) { try { String queryDb = "USE " + db + ";"; Statement stdb = conexion.createStatement(); @@ -102,15 +100,38 @@ public ResultSet select(String db, String table_name) { } catch (SQLException ex) { System.out.println(ex.getMessage()); - System.out.println("Error en la adquisicion de datos"); + JOptionPane.showMessageDialog(null, "Error en la adquisicion de datos"); return null; } } - // Delete - public void delete(String table_name_columna, String columna, String campo) { + // Delete + public static void delete(String db, String table_name, String column, String value) { try { - String query = "DELETE FROM " + table_name_columna + " WHERE " + columna + "= \"" + campo + "\""; + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "DELETE FROM " + table_name + " WHERE " + column + " = " + value; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error borrando el registro especificado"); + } + } + + // Delete + public static void update(String db, String table_name, String column, String value, String changes) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "UPDATE " + table_name + " SET " + changes + + " WHERE " + column + " = " + value + " "; Statement st = conexion.createStatement(); System.out.println(query); st.executeUpdate(query); diff --git a/Ejercicio1/src/main/java/models/DataBase.java b/Ejercicio1/src/main/java/models/DataBase.java new file mode 100644 index 0000000..591a31f --- /dev/null +++ b/Ejercicio1/src/main/java/models/DataBase.java @@ -0,0 +1,37 @@ +package models; + +/** + * @author Joan + */ +public class DataBase { + + public static Table cliente; + public static String DBNAME = "servicios"; + + public static void init() { + Attribute[] attributes = { + new Attribute("id", "INT(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("Nombre", "VARCHAR(250)", "NOT NULL"), + new Attribute("Apellido", "VARCHAR(250)", "NOT NULL"), + new Attribute("Direccion", "VARCHAR(250)", "NOT NULL"), + new Attribute("DNI", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("Fecha", "DATE", "DEFAULT NULL"), + }; + cliente = new Table("clientes", attributes, DBNAME); + + Connector.openConnection(); + Connector.createDB(DBNAME); + cliente.createTable(); + } + + + public static void main(String[] args) { + init(); + cliente.insert(new String[]{"Nombre", "Apellido", "Direccion"}, + new String[]{"anna","lapeyra","manila"}); + cliente.select(); + } + + + +} diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java new file mode 100644 index 0000000..831b11a --- /dev/null +++ b/Ejercicio1/src/main/java/models/Table.java @@ -0,0 +1,89 @@ +package models; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Joan + * Esta clase es una forma genérica de representar tablas SQL + * usable para otros ejercicios similares + */ +public class Table { + public String name; + public Attribute[] attributes; + public final String DBNAME; + + public Table(String name, Attribute[] attributes, String dbname) { + this.name = name; + this.attributes = attributes; + this.DBNAME = dbname; + } + + // retorna un array con los nombres de los atributos + public String[] getAttributeNames() { + String[] names = new String[attributes.length]; + for (int i = 0; i < names.length; i++) { + names[i] = attributes[i].name; + } + return names; + } + + // crea la tabla + public void createTable() { + String[] attributeStrings = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + attributeStrings[i] = attributes[i].toString(); + } + Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); + } + + // inserta un registro con los valores `values` en las respectivas columnas `columns` + public void insert(String[] columns, String[] values) { + Connector.insert(DBNAME, name, String.join(", ", columns), "'"+String.join("', '", values)+"'"); + } + + // retorna una matriz con todos los elementos + public List select() { + ResultSet resultSet = Connector.select(DBNAME,name); + List rows = new ArrayList<>(); + try { + while (resultSet.next()) { + String[] row = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + row[i] = resultSet.getString(attributes[i].name); + } + rows.add(row); + } + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + System.out.println("Error en la conversión de resultados a objetos Cliente"); + } + return rows; + } + + // elimina el registro cuyos valores (de todas las columnas) son `values` + public void delete(String[] values) { + Connector.delete(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", values)+"')" + ); + } + + // modifica el registro cuyos valores (de todas las columnas) son `current_values` + // asigna valores `new_values` a las respectivas columnas `new_values` + public void update(String[] current_values, String[] columns_to_update, String[] new_values) { + int n = columns_to_update.length; + String[] changes = new String[n]; + for (int i = 0; i < n; i++) { + changes[i] = columns_to_update[i] + " = '" + new_values[i] + "'"; + } + Connector.update(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", current_values)+"')", + String.join(", ", changes) + ); + } + +} diff --git a/Ejercicio1/src/main/java/views/Cliente_InsertView.java b/Ejercicio1/src/main/java/views/EditCliente_View.java similarity index 80% rename from Ejercicio1/src/main/java/views/Cliente_InsertView.java rename to Ejercicio1/src/main/java/views/EditCliente_View.java index 97fdf6a..fea96ab 100644 --- a/Ejercicio1/src/main/java/views/Cliente_InsertView.java +++ b/Ejercicio1/src/main/java/views/EditCliente_View.java @@ -3,7 +3,6 @@ */ package views; -import java.sql.Date; import java.time.LocalDate; import java.time.format.DateTimeFormatter; @@ -12,10 +11,9 @@ /** * @author Javier - * @param - * + * insert or update */ -public class Cliente_InsertView extends JFrame { +public class EditCliente_View extends JFrame { private JPanel contentPane; public JTextField nombre; @@ -23,10 +21,10 @@ public class Cliente_InsertView extends JFrame { public JTextField direccion; public JTextField dni; public JTextField fecha; - public JButton crear; - public Date date; + public JButton button; + public JLabel tituloVentana; - public Cliente_InsertView() { + public EditCliente_View() { initComponents(); } @@ -84,21 +82,13 @@ private void initComponents() { fecha.setBounds(107, 217, 201, 20); contentPane.add(fecha); - crear = new JButton("Crear"); - crear.setBounds(219, 307, 89, 23); - contentPane.add(crear); - - JLabel lblNewLabel = new JLabel("NUEVO CLIENTE"); - lblNewLabel.setBounds(124, 22, 138, 20); - contentPane.add(lblNewLabel); - - - - - - - + button = new JButton(); + button.setBounds(219, 250, 89, 23); + contentPane.add(button); + tituloVentana = new JLabel(); + tituloVentana.setBounds(124, 22, 138, 20); + contentPane.add(tituloVentana); } diff --git a/Ejercicio1/src/main/java/views/Cliente_Index.java b/Ejercicio1/src/main/java/views/IndexView.java similarity index 92% rename from Ejercicio1/src/main/java/views/Cliente_Index.java rename to Ejercicio1/src/main/java/views/IndexView.java index 3f9f04a..0629619 100644 --- a/Ejercicio1/src/main/java/views/Cliente_Index.java +++ b/Ejercicio1/src/main/java/views/IndexView.java @@ -4,13 +4,12 @@ import javax.swing.JFrame; import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JButton; -public class Cliente_Index extends JFrame { +public class IndexView extends JFrame { public JPanel contentPane; public JButton nuevoCliente; @@ -25,7 +24,7 @@ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { - Cliente_Index frame = new Cliente_Index(); + IndexView frame = new IndexView(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); @@ -38,7 +37,7 @@ public void run() { * Create the frame. */ - public Cliente_Index() { + public IndexView() { initComponents(); } diff --git a/Ejercicio1/src/main/java/views/Cliente_ListView.java b/Ejercicio1/src/main/java/views/ListView.java similarity index 52% rename from Ejercicio1/src/main/java/views/Cliente_ListView.java rename to Ejercicio1/src/main/java/views/ListView.java index 8feb237..8169fc3 100644 --- a/Ejercicio1/src/main/java/views/Cliente_ListView.java +++ b/Ejercicio1/src/main/java/views/ListView.java @@ -9,13 +9,15 @@ * @author Javier * */ -public class Cliente_ListView extends JFrame{ +public class ListView extends JFrame{ private JPanel contentPane; public JTable table; - public JButton add; + public JButton insert; + public JButton update; + public JButton delete; - public Cliente_ListView() { + public ListView() { initComponents(); } @@ -32,8 +34,16 @@ private void initComponents() { clientes.setBounds(188, 20, 49, 14); contentPane.add(clientes); - add = new JButton("Añadir"); - add.setBounds(319, 227, 89, 23); - contentPane.add(add); + insert = new JButton("Añadir"); + insert.setBounds(54, 227, 89, 23); + contentPane.add(insert); + + update = new JButton("Modificar"); + update.setBounds(165, 227, 89, 23); + contentPane.add(update); + + delete = new JButton("Eliminar"); + delete.setBounds(283, 227, 89, 23); + contentPane.add(delete); } } diff --git a/Ejercicio1/target/classes/META-INF/MANIFEST.MF b/Ejercicio1/target/classes/META-INF/MANIFEST.MF deleted file mode 100644 index 47543d1..0000000 --- a/Ejercicio1/target/classes/META-INF/MANIFEST.MF +++ /dev/null @@ -1,5 +0,0 @@ -Manifest-Version: 1.0 -Built-By: paula -Build-Jdk: 17.0.6 -Created-By: Maven Integration for Eclipse - diff --git a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties b/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties deleted file mode 100644 index ee5b32e..0000000 --- a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties +++ /dev/null @@ -1,7 +0,0 @@ -#Generated by Maven Integration for Eclipse -#Wed Apr 12 18:35:04 CEST 2023 -m2e.projectLocation=C\:\\Users\\paula\\eclipse-workspace\\UD22\\Ejercicio1 -m2e.projectName=ta22 -groupId=22 -artifactId=ta22 -version=0.0.1-SNAPSHOT diff --git a/Ejercicio2/.classpath b/Ejercicio2/.classpath new file mode 100644 index 0000000..f0257c5 --- /dev/null +++ b/Ejercicio2/.classpath @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Ejercicio2/.gitignore b/Ejercicio2/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/Ejercicio2/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/Ejercicio2/.project b/Ejercicio2/.project new file mode 100644 index 0000000..5e526a0 --- /dev/null +++ b/Ejercicio2/.project @@ -0,0 +1,34 @@ + + + ta22 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + + + 1681308613605 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/Ejercicio2/.settings/org.eclipse.core.resources.prefs b/Ejercicio2/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..f9fe345 --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/Ejercicio2/.settings/org.eclipse.jdt.apt.core.prefs b/Ejercicio2/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 0000000..d4313d4 --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/Ejercicio2/.settings/org.eclipse.jdt.core.prefs b/Ejercicio2/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..70d61cf --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,111 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.builder.annotationPath.allLocations=disabled +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.APILeak=warning +org.eclipse.jdt.core.compiler.problem.annotatedTypeArgumentToUnannotated=info +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.suppressWarningsNotFullyAnalysed=info +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled +org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unstableAutoModuleName=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/Ejercicio2/.settings/org.eclipse.m2e.core.prefs b/Ejercicio2/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/Ejercicio2/README.md b/Ejercicio2/README.md new file mode 100644 index 0000000..9cd3dc2 --- /dev/null +++ b/Ejercicio2/README.md @@ -0,0 +1 @@ +# UD22 \ No newline at end of file diff --git a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.xml b/Ejercicio2/pom.xml similarity index 100% rename from Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.xml rename to Ejercicio2/pom.xml diff --git a/Ejercicio2/src/main/java/app1Main/App.java b/Ejercicio2/src/main/java/app1Main/App.java new file mode 100644 index 0000000..0848eb8 --- /dev/null +++ b/Ejercicio2/src/main/java/app1Main/App.java @@ -0,0 +1,29 @@ +package app1Main; + +import javax.swing.*; +import controller.*; +import models.DataBase; + +/** + * @author Javier + * + */ +public class App { + public static void main( String[] args ) { + + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (UnsupportedLookAndFeelException e) { + } + catch (ClassNotFoundException e) { + } + catch (InstantiationException e) { + } + catch (IllegalAccessException e) { + } + + DataBase.init(); + new IndexController(); + } +} diff --git a/Ejercicio2/src/main/java/controller/EditClientes_Controller.java b/Ejercicio2/src/main/java/controller/EditClientes_Controller.java new file mode 100644 index 0000000..9fc95f5 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/EditClientes_Controller.java @@ -0,0 +1,99 @@ +/** + * + */ +package controller; + +import java.awt.event.*; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import javax.swing.*; + +import models.*; +import views.*; + +/** + * @author Joan + * Esta clase añade (insert) o modifica (update) un elemento de la tabla cliente + * Si elementToUpdate==null, inserta un nuevo elemento + * Si no, modifica el elemento cuyos campos son elementToUpdate + */ +public class EditClientes_Controller implements ActionListener { + + private EditClientes_View view; + private ListController listController; + private String[] elementToUpdate = null; + private Table table = DataBase.clientes; + + // insert cliente + public EditClientes_Controller(ListController listController) { + this.listController = listController; + initVista(); + view.setTitle("Nuevo cliente"); + view.tituloVentana.setText("NUEVO CLIENTE"); + view.button.setText("Añadir"); + } + + // update cliente + public EditClientes_Controller(ListController listController, String[] elementToUpdate) { + this.listController = listController; + this.elementToUpdate = elementToUpdate; + initVista(); + view.setTitle("Modificar cliente"); + view.tituloVentana.setText("MODIFICAR CLIENTE"); + view.button.setText("Modificar"); + + view.nombre.setText(elementToUpdate[1]); + view.apellidos.setText(elementToUpdate[2]); + view.direccion.setText(elementToUpdate[3]); + view.dni.setText(elementToUpdate[4]); + view.fecha.setText(elementToUpdate[5]); + } + + public void initVista() { + view = new EditClientes_View(); + view.button.addActionListener(this); + view.setBounds(300, 300, 354, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + String nombre = view.nombre.getText(); + String apellidos = view.apellidos.getText(); + String direccion = view.direccion.getText(); + int dni = 0; + java.sql.Date fecha = null; + + try { + dni = Integer.parseInt(view.dni.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El DNI debe ser un número entero"); + return; + } + try { + String fechaTexto = view.fecha.getText(); // Obtener el texto del campo de fecha + DateTimeFormatter formatoFecha = DateTimeFormatter.ofPattern("yyyy-MM-dd");//establecer el formato + LocalDate fechaLocal = LocalDate.parse(fechaTexto, formatoFecha); // Analizar el texto de la fecha y crear un objeto LocalDate a partir de ella + fecha = java.sql.Date.valueOf(fechaLocal); // Convertir el objeto LocalDate a un objeto java.sql.Date + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El formato de la fecha es incorrecto (formato deseado: aaaa-mm-dd)"); + return; + } + + String[] columns = {"nombre", "apellido", "direccion", "dni", "fecha"}; + String[] values = {nombre,apellidos,direccion,Integer.toString(dni),fecha.toString()}; + if (elementToUpdate == null) { + table.insert(columns, values); + } + else { + table.update(elementToUpdate, columns, values); + } + listController.refreshList(); + view.dispose(); + + } + + +} diff --git a/Ejercicio2/src/main/java/controller/EditVideos_Controller.java b/Ejercicio2/src/main/java/controller/EditVideos_Controller.java new file mode 100644 index 0000000..8db3e37 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/EditVideos_Controller.java @@ -0,0 +1,87 @@ +/** + * + */ +package controller; + +import java.awt.event.*; + +import javax.swing.JOptionPane; +import javax.swing.text.View; + +import models.*; +import views.*; + +/** + * @author Joan + * Esta clase añade (INSERT) o modifica (UPDATE) un elemento de la tabla cliente + * Si elementToUpdate==null, inserta un nuevo elemento + * Si no, modifica el elemento cuyos campos son elementToUpdate + */ +public class EditVideos_Controller implements ActionListener { + + private EditVideos_View view; + private ListController listController; + private String[] elementToUpdate = null; + private Table table = DataBase.videos; + + // insert cliente + public EditVideos_Controller(ListController listController) { + this.listController = listController; + initVista(); + view.setTitle("Nuevo vídeo"); + view.tituloVentana.setText("NUEVO VÍDEO"); + view.button.setText("Añadir"); + } + + // update cliente + public EditVideos_Controller(ListController listController, String[] elementToUpdate) { + this.listController = listController; + this.elementToUpdate = elementToUpdate; + initVista(); + view.setTitle("Modificar vídeo"); + view.tituloVentana.setText("MODIFICAR VÍDEO"); + view.button.setText("Modificar"); + + view.titulo.setText(elementToUpdate[1]); + view.director.setText(elementToUpdate[2]); + view.cli_id.setText(elementToUpdate[3]); + } + + public void initVista() { + view = new EditVideos_View(); + view.button.addActionListener(this); + view.seleccionarCliente.addActionListener(this); + view.setBounds(300, 300, 354, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.button) { + if (view.cli_id.getText() == "") { + JOptionPane.showMessageDialog(view, "Seleccione un cliente"); + } + + String titulo = view.titulo.getText(); + String director = view.director.getText(); + String cli_id = view.cli_id.getText(); + + String[] columns = {"titulo", "director", "cli_id"}; + String[] values = {titulo,director,cli_id}; + if (elementToUpdate == null) { + table.insert(columns, values); + } + else { + table.update(elementToUpdate, columns, values); + } + listController.refreshList(); + view.dispose(); + } + else { + new ListSelect_Controller(DataBase.clientes, view.cli_id); + } + } + + +} diff --git a/Ejercicio2/src/main/java/controller/IndexController.java b/Ejercicio2/src/main/java/controller/IndexController.java new file mode 100644 index 0000000..7435e0e --- /dev/null +++ b/Ejercicio2/src/main/java/controller/IndexController.java @@ -0,0 +1,42 @@ +package controller; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JFrame; +import javax.swing.border.EmptyBorder; + +import models.DataBase; +import views.IndexView; + +public class IndexController implements ActionListener{ + + private IndexView view; + + + + public IndexController() { + view = new IndexView(); + view.clientes.addActionListener(this); + view.videos.addActionListener(this); + initVista(); + } + + public void initVista() { + view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + view.setBounds(100, 100, 534, 473); + + view.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.clientes) { + new ListController(DataBase.clientes); + } else if (e.getSource() == view.videos) { + new ListController(DataBase.videos); + } + } + +} diff --git a/Ejercicio2/src/main/java/controller/ListController.java b/Ejercicio2/src/main/java/controller/ListController.java new file mode 100644 index 0000000..1c802a3 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/ListController.java @@ -0,0 +1,95 @@ +package controller; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import views.ListView; +import javax.swing.JOptionPane; +import javax.swing.table.DefaultTableModel; + +import models.DataBase; +import models.Table; + + + +public class ListController implements ActionListener { + + protected ListView view; + protected Table table; + + public ListController() {} + + public ListController(Table table) { + this.table = table; + view = new ListView(); + view.insert.addActionListener(this); + view.delete.addActionListener(this); + view.update.addActionListener(this); + initVista(); + refreshList(); + } + + public void initVista() { + view.setTitle("Lista de "+table.name); + view.setBounds(300, 300, 450, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + view.window_title.setText(table.name); + } + + public void refreshList() { + view.table.setModel(list()); + } + + private DefaultTableModel list() { + List rows = table.select(); + DefaultTableModel model = new DefaultTableModel(table.getAttributeNames(), 0); + for (String[] row : rows) { + model.addRow(row); + } + return model; + } + + private String[] getRowValues() { + int row = view.table.getSelectedRow(); + if (row == -1) { + JOptionPane.showMessageDialog(view, "Seleccione una fila"); + return null; + } + int n = view.table.getColumnCount(); + String[] values = new String[n]; + for (int i = 0; i < n; i++) { + values[i] = view.table.getValueAt(row, i).toString(); + } + return values; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.insert) { + if (table == DataBase.clientes) + new EditClientes_Controller(this); + else if (table == DataBase.videos) + new EditVideos_Controller(this); + } + else if (e.getSource() == view.update) { + String[] row_values = getRowValues(); + if (row_values != null) { + if (table == DataBase.clientes) + new EditClientes_Controller(this, row_values); + else if (table == DataBase.videos) + new EditVideos_Controller(this, row_values); + } + } + else if (e.getSource() == view.delete) { + String[] row_values = getRowValues(); + if (row_values != null) { + if (0 == JOptionPane.showConfirmDialog(view, "¿Está seguro de que quiere eliminar este cliente?")) { + table.delete(row_values); + refreshList(); + } + } + } + + } +} diff --git a/Ejercicio2/src/main/java/controller/ListSelect_Controller.java b/Ejercicio2/src/main/java/controller/ListSelect_Controller.java new file mode 100644 index 0000000..b6ede77 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/ListSelect_Controller.java @@ -0,0 +1,42 @@ +package controller; + +import views.ListSelect_View; + +import java.awt.event.ActionEvent; + +import javax.swing.JLabel; +import javax.swing.JOptionPane; + +import models.Table; + +/** + * @author Joan + * Esta clase se usa cuando hay que definir una Foregin Key + * Se abre una vista que muestra todos los registros de la tabla + * a la que apunta la Foregin Key y el usuario selecciona uno. + */ +public class ListSelect_Controller extends ListController { + + private JLabel result; // label donde irá el resultado de la selección + + public ListSelect_Controller(Table table, JLabel result) { + this.table = table; + this.result = result; + view = new ListSelect_View(); + view.select.addActionListener(this); + initVista(); + refreshList(); + } + + @Override + public void actionPerformed(ActionEvent e) { + int row = view.table.getSelectedRow(); + if (row == -1) { + JOptionPane.showMessageDialog(view, "Seleccione una fila"); + return; + } + String value = view.table.getValueAt(row, 0).toString(); //asumimos que la PK es la primera columna + result.setText(value); + view.dispose(); + } +} diff --git a/Ejercicio2/src/main/java/models/Attribute.java b/Ejercicio2/src/main/java/models/Attribute.java new file mode 100644 index 0000000..ed82e06 --- /dev/null +++ b/Ejercicio2/src/main/java/models/Attribute.java @@ -0,0 +1,31 @@ +package models; + +/** + * @author Joan + * esta clase representa el atributo de una tabla de una BD + */ +public class Attribute { + public String name; + public String type; + public String others = ""; + + // example: JEFE CHARVAR(30) NOT NULL REFERENCES EMPLEADO + // name="JEFE", type="CHARVAR", type_cardinality="(30)", + // others=["NOT", "NULL", "REFERENCES", "EMPLEADO"] + + + Attribute(String name, String type) { + this.name = name; + this.type = type; + } + Attribute(String name, String type, String others) { + this.name = name; + this.type = type; + this.others = others; + } + + @Override + public String toString() { + return name + " " + type + " " + others; + } +} diff --git a/Ejercicio2/src/main/java/models/Cliente.java b/Ejercicio2/src/main/java/models/Cliente.java new file mode 100644 index 0000000..be06d27 --- /dev/null +++ b/Ejercicio2/src/main/java/models/Cliente.java @@ -0,0 +1,148 @@ +/** + * + */ +package models; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +/** + * @author Javier + * + */ +public class Cliente { + + // Atributes + private int id; + private String nombre; + private String apellido; + private String direccion; + private int dni; + private Date fecha; + + private static final String DBNAME = "servicios"; + private static final String TBNAME = "clientes"; + + // Constructor + + public Cliente() { + } + + public Cliente(int id, String nombre, String apellido, String direccion, int dni, Date fecha) { + + this.id = id; + this.nombre = nombre; + this.apellido = apellido; + this.direccion = direccion; + this.dni = dni; + this.fecha = fecha; + + createDatabase(); + createTable(); + } + + // Methods + /** + * This method create de database if exists. + */ + public void createDatabase() { + Connector.createDB(DBNAME); + } + + /** + * This method create table "clientes". + */ + public void createTable() { + Connector.createTable(DBNAME, TBNAME, + "id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY," + + "nombre VARCHAR(250) NOT NULL," + + "apellido VARCHAR(250) NOT NULL," + + "direccion VARCHAR(250) NOT NULL," + + "dni INT(11) DEFAULT NULL," + + "fecha DATE DEFAULT NULL"); + } + + /** + * This method insert data into database. + */ + public void insert() { + Connector.insert(DBNAME, TBNAME, + "nombre, apellido, direccion, dni, fecha", + "'" + this.nombre + "', '" + this.apellido + "', '" + this.direccion + "', " + this.dni + ", '" + this.fecha + "'"); + } + + /* + * This method select data. + */ + public List select() { + ResultSet resultSet = Connector.select(DBNAME,TBNAME); + List clientes = new ArrayList<>(); + try { + while (resultSet.next()) { + Cliente c = new Cliente( + resultSet.getInt("id"), + resultSet.getString("nombre"), + resultSet.getString("apellido"), + resultSet.getString("direccion"), + resultSet.getInt("dni"), + resultSet.getDate("fecha")); + clientes.add(c); + } + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + System.out.println("Error en la conversión de resultados a objetos Cliente"); + } + return clientes; + } + + 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; + } + + public String getApellido() { + return apellido; + } + + public void setApellido(String apellido) { + this.apellido = apellido; + } + + public String getDireccion() { + return direccion; + } + + public void setDireccion(String direccion) { + this.direccion = direccion; + } + + public int getDni() { + return dni; + } + + public void setDni(int dni) { + this.dni = dni; + } + + public Date getFecha() { + return fecha; + } + + public void setFecha(Date fecha) { + this.fecha = fecha; + } + + +} diff --git a/Ejercicio2/src/main/java/models/Connector.java b/Ejercicio2/src/main/java/models/Connector.java new file mode 100644 index 0000000..4430c8b --- /dev/null +++ b/Ejercicio2/src/main/java/models/Connector.java @@ -0,0 +1,144 @@ +package models; + +import java.sql.*; +import java.util.logging.*; +import javax.swing.JOptionPane; + + + +public class Connector { + + private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; + private static final String URL = Credenciales.URL; + private static final String USER = Credenciales.USER; + private static final String PASSWORD = Credenciales.PASSWORD; + private static Connection conexion = null; + + public static void openConnection() { + try { + Class.forName(DRIVER); + conexion = DriverManager.getConnection(URL, USER, PASSWORD); + System.out.println("Server Connected"); + } catch(SQLException | ClassNotFoundException ex) { + System.out.print("No se ha podido conectar con mi base de datos"); + System.out.println(ex); + } + } + + public static void closeConnection() { + try { + conexion.close(); + JOptionPane.showMessageDialog(null, "Se ha finalizado la conexion con el servidor"); + } catch (SQLException ex) { + Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + } + } + + // Create database + public static void createDB(String dbName) { + try { + String query = " CREATE DATABASE IF NOT EXISTS " + dbName + " ;"; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + System.out.println("\tSe ha creado la base de datos " + dbName + " correctamente"); + } catch (SQLException ex) { + Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + } + } + + // Create table + public static void createTable(String nombreBBDD, String nombreTabla, String tablaColum) { + try { + String queryDb = "USE " + nombreBBDD + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "CREATE TABLE IF NOT EXISTS " + nombreTabla + " (" + tablaColum + ");"; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + System.out.println("\tSe ha creado la tabla " + nombreTabla + " correctamente"); + } catch (SQLException ex) { + Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + JOptionPane.showMessageDialog(null, "Error creando la tabla " + nombreTabla); + } + } + + // Insert row to table table + public static void insert(String dbName, String tableName, String columns, String values) { + try { + String queryDb = "USE " + dbName + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "INSERT INTO " + tableName + " (" + columns + ") VALUES (" + values + ");"; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + System.out.println("\tDatos insertados correctamente en la tabla " + tableName); + } catch (SQLException ex) { + //Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error insertando datos en la tabla"); + } + } + + // Select all rows from table + public static ResultSet select(String db, String table_name) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "SELECT * FROM " + table_name; + Statement st = conexion.createStatement(); + System.out.println(query); + return st.executeQuery(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error en la adquisicion de datos"); + return null; + } + } + + // Delete + public static void delete(String db, String table_name, String column, String value) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "DELETE FROM " + table_name + " WHERE " + column + " = " + value; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error borrando el registro especificado"); + } + } + + // Delete + public static void update(String db, String table_name, String column, String value, String changes) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "UPDATE " + table_name + " SET " + changes + + " WHERE " + column + " = " + value + " "; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error borrando el registro especificado"); + } + } +} \ No newline at end of file diff --git a/Ejercicio2/src/main/java/models/DataBase.java b/Ejercicio2/src/main/java/models/DataBase.java new file mode 100644 index 0000000..9ab26b3 --- /dev/null +++ b/Ejercicio2/src/main/java/models/DataBase.java @@ -0,0 +1,41 @@ +package models; + +/** + * @author Joan + * + */ +public class DataBase { + + // para ser consistente con ListSelect_Controller una tabla que es referenciada por otra + // debe tener una sola Primary Key, que tiene que ser el primer areibuto + + public static String DBNAME = "UD22_EJ2"; + public static Table clientes; + public static Table videos; + + public static void init() { + Attribute[] att_cliente = { + new Attribute("id", "INT(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("nombre", "VARCHAR(250)", "NOT NULL"), + new Attribute("apellido", "VARCHAR(250)", "NOT NULL"), + new Attribute("direccion", "VARCHAR(250)", "NOT NULL"), + new Attribute("dni", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("fecha", "DATE", "DEFAULT NULL"), + }; + clientes = new Table("clientes", att_cliente, DBNAME); + Attribute[] att_video = { + new Attribute("id", "INT(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("titulo", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("director", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("cli_id", "INT(11)", "DEFAULT NULL REFERENCES clientes(id)") + }; + videos = new Table("videos", att_video, DBNAME); + + Connector.openConnection(); + Connector.createDB(DBNAME); + clientes.createTable(); + videos.createTable(); + } + + +} diff --git a/Ejercicio2/src/main/java/models/Table.java b/Ejercicio2/src/main/java/models/Table.java new file mode 100644 index 0000000..831b11a --- /dev/null +++ b/Ejercicio2/src/main/java/models/Table.java @@ -0,0 +1,89 @@ +package models; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Joan + * Esta clase es una forma genérica de representar tablas SQL + * usable para otros ejercicios similares + */ +public class Table { + public String name; + public Attribute[] attributes; + public final String DBNAME; + + public Table(String name, Attribute[] attributes, String dbname) { + this.name = name; + this.attributes = attributes; + this.DBNAME = dbname; + } + + // retorna un array con los nombres de los atributos + public String[] getAttributeNames() { + String[] names = new String[attributes.length]; + for (int i = 0; i < names.length; i++) { + names[i] = attributes[i].name; + } + return names; + } + + // crea la tabla + public void createTable() { + String[] attributeStrings = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + attributeStrings[i] = attributes[i].toString(); + } + Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); + } + + // inserta un registro con los valores `values` en las respectivas columnas `columns` + public void insert(String[] columns, String[] values) { + Connector.insert(DBNAME, name, String.join(", ", columns), "'"+String.join("', '", values)+"'"); + } + + // retorna una matriz con todos los elementos + public List select() { + ResultSet resultSet = Connector.select(DBNAME,name); + List rows = new ArrayList<>(); + try { + while (resultSet.next()) { + String[] row = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + row[i] = resultSet.getString(attributes[i].name); + } + rows.add(row); + } + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + System.out.println("Error en la conversión de resultados a objetos Cliente"); + } + return rows; + } + + // elimina el registro cuyos valores (de todas las columnas) son `values` + public void delete(String[] values) { + Connector.delete(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", values)+"')" + ); + } + + // modifica el registro cuyos valores (de todas las columnas) son `current_values` + // asigna valores `new_values` a las respectivas columnas `new_values` + public void update(String[] current_values, String[] columns_to_update, String[] new_values) { + int n = columns_to_update.length; + String[] changes = new String[n]; + for (int i = 0; i < n; i++) { + changes[i] = columns_to_update[i] + " = '" + new_values[i] + "'"; + } + Connector.update(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", current_values)+"')", + String.join(", ", changes) + ); + } + +} diff --git a/Ejercicio2/src/main/java/views/EditClientes_View.java b/Ejercicio2/src/main/java/views/EditClientes_View.java new file mode 100644 index 0000000..38e1914 --- /dev/null +++ b/Ejercicio2/src/main/java/views/EditClientes_View.java @@ -0,0 +1,95 @@ +/** + * + */ +package views; + + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import javax.swing.*; + +/** + * @author Javier + * insert or update + */ +public class EditClientes_View extends JFrame { + + private JPanel contentPane; + public JTextField nombre; + public JTextField apellidos; + public JTextField direccion; + public JTextField dni; + public JTextField fecha; + public JButton button; + public JLabel tituloVentana; + + public EditClientes_View() { + initComponents(); + } + + private void initComponents() { + + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + JLabel lNombre = new JLabel("Nombre:"); + lNombre.setBounds(34, 56, 61, 14); + contentPane.add(lNombre); + + JLabel lApellidos = new JLabel("Apellidos:"); + lApellidos.setBounds(34, 100, 61, 14); + contentPane.add(lApellidos); + + JLabel lDireccion = new JLabel("Dirección:"); + lDireccion.setBounds(34, 142, 61, 14); + contentPane.add(lDireccion); + + JLabel lDni = new JLabel("DNI:"); + lDni.setBounds(34, 183, 46, 14); + contentPane.add(lDni); + + JLabel lFecha = new JLabel("Fecha:"); + lFecha.setBounds(34, 220, 46, 14); + contentPane.add(lFecha); + + nombre = new JTextField(); + nombre.setBounds(107, 53, 201, 20); + contentPane.add(nombre); + nombre.setColumns(10); + + apellidos = new JTextField(); + apellidos.setColumns(10); + apellidos.setBounds(107, 97, 201, 20); + contentPane.add(apellidos); + + direccion = new JTextField(); + direccion.setColumns(10); + direccion.setBounds(107, 139, 201, 20); + contentPane.add(direccion); + + dni = new JTextField(); + dni.setColumns(10); + dni.setBounds(107, 180, 201, 20); + contentPane.add(dni); + + fecha = new JTextField(); + //creamos una fecha actual por defecto + DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + fecha.setText(LocalDate.now().format(dateFormat)); + fecha.setColumns(10); + fecha.setBounds(107, 217, 201, 20); + contentPane.add(fecha); + + button = new JButton(); + button.setBounds(219, 250, 89, 23); + contentPane.add(button); + + tituloVentana = new JLabel(); + tituloVentana.setBounds(124, 22, 138, 20); + contentPane.add(tituloVentana); + + + } +} \ No newline at end of file diff --git a/Ejercicio2/src/main/java/views/EditVideos_View.java b/Ejercicio2/src/main/java/views/EditVideos_View.java new file mode 100644 index 0000000..5d1e1a7 --- /dev/null +++ b/Ejercicio2/src/main/java/views/EditVideos_View.java @@ -0,0 +1,73 @@ +/** + * + */ +package views; + +import javax.swing.*; + +/** + * @author Javier + * insert or update + */ +public class EditVideos_View extends JFrame { + + private JPanel contentPane; + public JTextField titulo; + public JTextField director; + public JButton seleccionarCliente; + public JLabel cli_id; + public JButton button; + public JLabel tituloVentana; + + public EditVideos_View() { + initComponents(); + } + + private void initComponents() { + + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + tituloVentana = new JLabel(); + tituloVentana.setBounds(124, 22, 138, 20); + contentPane.add(tituloVentana); + + button = new JButton(); + button.setBounds(219, 195, 89, 23); + contentPane.add(button); + + JLabel lTitulo = new JLabel("Título:"); + lTitulo.setBounds(34, 56, 61, 14); + contentPane.add(lTitulo); + + JLabel lDirector = new JLabel("Director:"); + lDirector.setBounds(34, 100, 61, 14); + contentPane.add(lDirector); + + JLabel lCliente = new JLabel("Cliente:"); + lCliente.setBounds(34, 142, 61, 14); + contentPane.add(lCliente); + + titulo = new JTextField(); + titulo.setBounds(107, 53, 201, 20); + contentPane.add(titulo); + titulo.setColumns(10); + + director = new JTextField(); + director.setColumns(10); + director.setBounds(107, 97, 201, 20); + contentPane.add(director); + + seleccionarCliente = new JButton("Seleccionar cliente"); + seleccionarCliente.setBounds(105, 138, 150, 23); + contentPane.add(seleccionarCliente); + + cli_id = new JLabel(""); + cli_id.setBounds(260, 142, 20, 14); + contentPane.add(cli_id); + + + + } +} \ No newline at end of file diff --git a/Ejercicio2/src/main/java/views/IndexView.java b/Ejercicio2/src/main/java/views/IndexView.java new file mode 100644 index 0000000..52d9d76 --- /dev/null +++ b/Ejercicio2/src/main/java/views/IndexView.java @@ -0,0 +1,51 @@ +package views; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JLabel; +import java.awt.Font; +import javax.swing.SwingConstants; +import javax.swing.JButton; + +public class IndexView extends JFrame { + + public JPanel contentPane; + public JButton clientes; + public JButton videos; + + /** + * Create the frame. + */ + + public IndexView() { + initComponents(); + } + + public void initComponents() { + + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + JPanel panel = new JPanel(); + panel.setBounds(267, 14, 1, 1); + contentPane.add(panel); + panel.setLayout(null); + + JLabel lblBienvenido = new JLabel("Gestor de clientes y películas"); + lblBienvenido.setHorizontalAlignment(SwingConstants.CENTER); + lblBienvenido.setFont(new Font("Tahoma", Font.BOLD, 18)); + lblBienvenido.setBounds(86, 26, 329, 62); + contentPane.add(lblBienvenido); + + clientes = new JButton("Clientes"); + clientes.setFont(new Font("Tahoma", Font.PLAIN, 16)); + clientes.setBounds(180, 100, 144, 40); + contentPane.add(clientes); + + videos = new JButton("Vídeos"); + videos.setFont(new Font("Tahoma", Font.PLAIN, 16)); + videos.setBounds(180, 166, 144, 40); + contentPane.add(videos); + } +} diff --git a/Ejercicio2/src/main/java/views/ListSelect_View.java b/Ejercicio2/src/main/java/views/ListSelect_View.java new file mode 100644 index 0000000..da55727 --- /dev/null +++ b/Ejercicio2/src/main/java/views/ListSelect_View.java @@ -0,0 +1,17 @@ +package views; + +import javax.swing.*; + +/** + * @author Joan + * + */ +public class ListSelect_View extends ListView { + public ListSelect_View() { + initComponents(); + + select = new JButton("Aceptar"); + select.setBounds(165, 227, 89, 23); + contentPane.add(select); + } +} diff --git a/Ejercicio2/src/main/java/views/ListView.java b/Ejercicio2/src/main/java/views/ListView.java new file mode 100644 index 0000000..d3f3cde --- /dev/null +++ b/Ejercicio2/src/main/java/views/ListView.java @@ -0,0 +1,54 @@ +/** + * + */ +package views; + +import javax.swing.*; + +/** + * @author Javier + * + */ +public class ListView extends JFrame{ + + protected JPanel contentPane; + public JTable table; + public JButton insert; + public JButton update; + public JButton delete; + public JButton select; // solo se usa en la subclase ListSelect_View + public JLabel window_title; + + public ListView() { + initComponents(); + initButtons(); + } + + protected void initComponents() { + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + table = new JTable(); + table.setBounds(20, 45, 388, 171); + contentPane.add(table); + + window_title = new JLabel(); + window_title.setBounds(188, 20, 49, 14); + contentPane.add(window_title); + } + + private void initButtons() { + insert = new JButton("Añadir"); + insert.setBounds(54, 227, 89, 23); + contentPane.add(insert); + + update = new JButton("Modificar"); + update.setBounds(165, 227, 89, 23); + contentPane.add(update); + + delete = new JButton("Eliminar"); + delete.setBounds(283, 227, 89, 23); + contentPane.add(delete); + } +} diff --git a/Ejercicio2/src/test/java/app1Main/AppTest.java b/Ejercicio2/src/test/java/app1Main/AppTest.java new file mode 100644 index 0000000..67ca083 --- /dev/null +++ b/Ejercicio2/src/test/java/app1Main/AppTest.java @@ -0,0 +1,38 @@ +package app1Main; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +}