Está en la página 1de 29

UNIVERSIDAD ABIERTA Y A DISTANCIA DE MÉXICO

ASIGNATURA:
Programación orientada a objetos II

Actividad 4. Menús y ventanas

ALUMNO:

Ángel Genaro Trujillo Marín


DOCENTE:
Alicia Guadalupe Robertos Pinto
MATRÍCULA:
ES1822024128

17de febrero de 2020

1
Introducción
La actividad es una continuación de lo visto en la actividad 3, en este caso nos habla de crear 5
botones y en listado dentro de un JFrame con la finalidad de poder visualizar lo que hemos
capturado o guardado. En mi caso en la actividad pasada, realice capturas de datos bajo un
contenedor y un constructor en donde podía visualizar las ventas que se generaban, y asi llevar
un registro, además de poder editarlas.
En este casovoy a trabajar con la creación de usuario o empleados, esto con el fin de poder
desarrollar la actividad, se va hacer la creación de un JFrame y posteriormente el diseño de la
interfaz gráfica, dentro del código se creará un arreglo de 4 posiciones para el listado que se
ingresó para que cuando demos de alta un dato podamos visualizar lo que estamos guardado,
así mismo poder eliminarlo, o eliminar todo el listado registrado.

2
Indicaciones
1. Investiga y menciona los diferentes tipos de menú y ventanas que existen por lo menos 4, así
como su estructura algorítmica (pasos) y sintáctica (código).

Todo documento que envíes para ser evaluado deber tener las citas textuales de lo contrario
el trabajo tendría cero.
2. Crea la interfaz gráfica en NetBeans 7.1 o superior, con el menú principal (Inventario,
Personal, nómina y Salir); desarrolla el submenú inventario, para ello debes realizar lo siguiente:
3. Crea tres opciones en el submenú inventario (altas, bajas, modificaciones)
4. Seleccionar altas y crear un formulario en el JframeForm con los siguientes datos (Código,
articulo, sucursal, existencia y marca)
5. Crear los Label, TextField y form necesario para el formulario.
6. Seleccionar bajas y crear un formulario en el JframeForm con los siguientes datos (No. Código y
sucursal
7. Crear los Label, TextField y form necesario para el formulario.
8. Seleccionar modificar y crear un formulario en el JframeForm con los siguientes datos (No.
código, articulo, sucursal, existencia y marca)
9. Crear los Label, TextField y form necesario para el formulario.
10. Selecciona el menú personal y crear tres opciones (Altas, bajas y modificaciones).
11. Selecciona altas y crear un formulario en el JframeForm con los siguientes datos (Matricula,
Nombre, Apellidos, Edad, Puesto y Área)
12. Crear los Label, TextField y form necesario para el formulario.
13. Selecciona bajas y crear un formulario en el JframeForm con los siguientes datos (Matricula)

14. Crear los Label, TextField y form necesario para el formulario.


15. Selecciona modificar y crear un formulario en el JframeForm con los siguientes datos
(Matricula, Nombre, Apellidos, Edad, Puesto y Área)
16. Crear los Label, TextField y form necesario para el formulario.
17. Envía las capturas de pantallas que permitan entender mejor tu proyecto, es importante que en
cada captura de pantalla agregues una descripción para conocer a detalle el seguimiento de lo que
estás realizando en tu proyecto.
18. Documenta el código que estás realizando en NetBeans, es muy importante que copies y
pegues el código que estás realizando y hagas la descripción a detalle de cada sección de tal
manera que cualquier persona lo pueda entender.
19. Se recomienda enumerar los puntos realizados en el informe para evitar confusión en la
calificación.
20. En la plataforma debes enviar dos archivos:
21. Primero es un informe (con las características siguientes) : Carátula “Logotipo Universidad,
nombre del Docente, nombre del estudiante, fecha de entrega, unidad y actividad”, Índice,
Introducción como mínimo de 100 palabras, contenido de la tarea mínimo 5 cuartillas,
conclusión como mínimo de 100 palabras; justificar párrafo de texto de forma homogénea
entre los márgenes, todas las hojas deben estar enumeradas, Bibliografía en formato APA,
integrar en la investigación al menos tres fuentes confiables, es obligatorio agregar la
actividad en la tarea.
22. Segundo archivo: tienes que enviar el código que estás realizando en NetBeans (Proyecto en
formato ZIP o RAR).
23. Posteriormente guarda tu actividad con la nomenclatura DPO2_U2_A4_XXYZ. Sustituye las XX
por las dos primeras letras de tu primer nombre, la Y por tu primer apellido y la Z por tu segundo
apellido.

3
Índice
Índice ................................................................................................................................................. 4
Tipos de menú y ventanas ........................................................................................................... 5
Clase JFrame Acceso ................................................................................................................... 7
Inicio de programación ................................................................................................................. 7
Código Acceso ................................................................................................................................ 8
Captura de pantalla de JFrame Recursos humanos con botones, y listado ............... 16
Conclusiones................................................................................................................................. 30
Bibliografía ..................................................................................................................................... 31

4
Tipos de menú y ventanas
En la unidad ya hemos estado trabajando con componentes atómicos y los componentes de
texto, cuando hablamos de tipo de menú nos encontramos:

JMenuBar.
Es el elemento principal cuando vamos a crear menús, ya que provee la barra donde se alojarán
cada uno de los items u opciones deseadas.
Estructura Sintáctica
1 barraMenu = newJMenuBar();
2 barraMenu.add(menuArchivo);
3 setJMenuBar(barraMenu);
Ejemplo

Recuperado de http://codejavu.blogspot.com/2013/09/menus-con-java-swing.html

JMenu.
Si bien el elemento anterior permite crear una Barra donde alojar el resto de componentes, el
JMenu es quien contiene dichos componentes, a este se le agregan el resto de opciones,
podemos asociarlo con un contenedor el cual aloja otros elementos como botones, etiquetas,
campos entre otros, el JMenu permite agregar los elementos o items correspondientes, así como
otros JMenus.
Estructura sintáctica
1 menuArchivo = newJMenu();
2 menuArchivo.add(menuItemNuevo);
3 menuArchivo.addSeparator();

Ejemplo

Recuperado de http://codejavu.blogspot.com/2013/09/menus-con-java-swing.html

5
JMenuItem.
Representan Items u opciones del menú, cuando creamos un JMenu decimos que tipo de
opciones puede contener y al crear un JMenuItem decimos cuales son las opciones para ese
menú en específico, por ejemplo, el Menú "Archivo", contendrá los items "Abrir", "Guardar",
"Nuevo", "Principal", etc.
Estructura sintáctica
1 menuItemNuevo = newJMenuItem();
2 menuItemNuevo.setText("Nuevo");
3 menuArchivo.add(menuItemNuevo);

Ejemplo

Recuperado dehttp://codejavu.blogspot.com/2013/09/menus-con-java-swing.html
JCheckBoxMenuItem.
Este componte es otro item que almacena el JMenu, permite vincular casillas de verificación o
Checkbox, muy útil cuando vamos a parametrizar más de una opción o característica de nuestro
sistema.
Estructura sintáctica
1 jCheckMenu1 = newJCheckBoxMenuItem("Check1");
2 menuOpciones.add(jCheckMenu1);

Ejemplo

Recuperado de http://codejavu.blogspot.com/2013/09/menus-con-java-swing.html

6
Estos mencionados son algunos de los menú y ventanas que podemos encontrar en java en las
clases Swing. Cabe señalar que dentro de una clase JFrame podemos diseñar nuestras propias
ventanas y anexar los botones y características que vayamos necesitando. Continuado con el
desarrollo del proyecto planteando, vamos a continuar con los sub-menú y ventanas de ventas
en mi caso en la actividad pasada logré terminar esta parte, en donde se creó un constructor y
un contenedor para almacenar los registros de la información, donde seguimiento en este caso
empezó a programa el alta de empleado en donde se usará una lista dentro de una venta para
poder visualizar lo que hemos estado creando.
Inicio de programación
Antes de poder ingresar a ese JFrame cree otro donde se dará acceso para la creación de un
empleado o baja, pues considero que solo el administrador de software o personal de recursos
humanos pueden realizar este proceso.
Clase JFrame Acceso
Esta clase contiene 1 JTextField en donde se ingresarán los datos de usuario y contraseña está
basado en Password Field, para que no se vean los dígitos que se ingresan
El Usuario es: Ange
lContraseña: 1234

Además, contiene una barra de menú que te puede enlazar a ventas o bien salir del programa,
un botón para regresar al menú principal

7
Código Acceso
public class Acceso extends javax.swing.JFrame {

/**
* Creates new form acceso
*/
public Acceso() {
setLayout(null);
setTitle("Acceso"); //se le da un título a la ventana
setIconImage(new ImageIcon(getClass().getResource("/imagenes/icon.png")).getImage());
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel1 = new javax.swing.JLabel();


jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
PantallaUser = new javax.swing.JTextField();
jButton3 = new javax.swing.JButton();
jPasswordField1 = new javax.swing.JPasswordField();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();

8
jMenuItem1 = new javax.swing.JMenuItem();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setBackground(new java.awt.Color(153, 153, 153));


jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel1.setText("Usuario");

jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N


jLabel2.setText("Contraseña");

jButton1.setText("Ingresar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jButton1ActionPerformed(evt);
}
});

jLabel3.setBackground(new java.awt.Color(0, 51, 255));


jLabel3.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
jLabel3.setText("Para poder ingresar a esta opción ingresa tu usuario de recursos
humanos");

PantallaUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
PantallaUserActionPerformed(evt);
}
});

jButton3.setText("Regresar");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jButton3ActionPerformed(evt);
}

9
});

jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jPasswordField1ActionPerformed(evt);
}
});

jMenu1.setText("Menú");

jMenuItem1.setText("Salir");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);

jMenuBar1.add(jMenu1);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()

10
.addContainerGap()
.addComponent(jButton3)
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PantallaUser, javax.swing.GroupLayout.PREFERRED_SIZE, 156,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel1))
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 156,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(169, 169, 169)
.addComponent(jButton1)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel3)
.addGap(24, 24, 24)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PantallaUser, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

11
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32,
Short.MAX_VALUE)
.addComponent(jButton3)
.addContainerGap())
);

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

private void jMenuItem1ActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:
}

private void jButton1ActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:
String Usuario = "Angel"; //declaración de variables para acceso
String Contraseña = "1234";
String User;
String Pass;

User = PantallaUser.getText();//se va almacenar datos las contraseñas para dar acceso


Pass = jPasswordField1.getText();

if(PantallaUser.getText().equals(Usuario)&&jPasswordField1.getText().equals(Contraseña))
//condición de comparación de datos
{
RecursosHumanos P1 = new RecursosHumanos();
P1.setVisible(true);
dispose();

12
}
else {
Error P=new Error();
P.setVisible(true);
dispose();
}
}

private void PantallaUserActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:
}

private void jButton3ActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:

Principal W1=new Principal(); //retorno de botonacceso principal


W1.setVisible(true);
dispose();
}

private void jPasswordField1ActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:

/**
* @paramargs the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and
feel.

13
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Acceso.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Acceso.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Acceso.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Acceso.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
}
//</editor-fold>
//</editor-fold>

/* Create and display the form */


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

14
// Variables declaration - do not modify
private javax.swing.JTextFieldPantallaUser;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JPasswordField jPasswordField1;
// End of variables declaration
}

JFrame Recursos Humanos


En este apartado se va estar trabajando la interfaz en la que vamos a dar de alta a un empleado,
o ver los empleados que están regstrados, así como la posibilidad de eliminar, o borrar todo el
contenido de la lista, para ello se va ser uso de varios label, JTextField, Button, y un JList en este
se va declarar lo nombres que deben tener las columnas, según los campos o datos a captura
para poder mediante un arreglo de posiciones guardar datos, y manipularlos con los botones.
Captura de pantalla de JFrame Recursos humanos con botones, y listado

15
16
Captura de datos en listado dentro de un JFrame

En la imágenes se pude detectar como podemos ingresar los datos y visualizarlo de manera
directa en un listado, también se podría quitar ese listado crear un botón en donde el listado se
vea desde un JFrame nuevo en una ventana nueva, sin embargo por utilidad se deja así para ser
más eficaces.
Cabe mencionar que hay que programar todo el botón para que hagan lo que se está solicitando.

Código
publicRecursosHumanos() {
setLayout(null);
setTitle("Alta o baja empleados"); //se le da un título a la ventana
setIconImage(new ImageIcon(getClass().getResource("/imagenes/icon.png")).getImage());
initComponents();

model.addColumn("ID"); //se le asigna nombre a las columnas segun espacio que


ocupemos
model.addColumn("Nombre");

17
model.addColumn("Apellido");
model.addColumn("Sexo");
this.tabladedatos.setModel(model);

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel2 = new javax.swing.JLabel();


jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtid = new javax.swing.JTextField();
txtnombre = new javax.swing.JTextField();
txtapellidos = new javax.swing.JTextField();
btnagregar = new javax.swing.JButton();
btnnuevo = new javax.swing.JButton();
btneleminar = new javax.swing.JButton();
btneleminartodo = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tabladedatos = new javax.swing.JTable();
sexo = new javax.swing.JComboBox<>();
btnsalir = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();

18
jMenu2 = new javax.swing.JMenu();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel2.setText("ID:");

jLabel3.setText("Nombre:");

jLabel4.setText("Apellidos:");

jLabel5.setText("Sexo:");

btnagregar.setText("Agregar");
btnagregar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
btnagregarActionPerformed(evt);
}
});

btnnuevo.setText("Nuevo");
btnnuevo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
btnnuevoActionPerformed(evt);
}
});

btneleminar.setText("Eliminar");
btneleminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
btneleminarActionPerformed(evt);
}
});

btneleminartodo.setText("EliminarTodo");

19
btneleminartodo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
btneleminartodoActionPerformed(evt);
}
});

tabladedatos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(tabladedatos);

sexo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Seleccionar:",


"Masculino", "Femenino" }));

btnsalir.setText("Salir");
btnsalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
btnsalirActionPerformed(evt);
}
});

jMenu1.setText("Menú");

jMenuItem1.setText("Ventas");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {

20
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);

jMenuItem2.setText("Salir");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);

jMenuBar1.add(jMenu1);

jMenu2.setText("Ayuda");
jMenuBar1.add(jMenu2);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0,
Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(9, 9, 9)

21
.addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, 89,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(31, 31, 31)
.addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE, 89,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(22, 22, 22)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
false)
.addComponent(txtapellidos)
.addComponent(sexo, 0, 89, Short.MAX_VALUE))))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
false)
.addComponent(btnagregar, javax.swing.GroupLayout.DEFAULT_SIZE, 82,
Short.MAX_VALUE)
.addComponent(btneleminar, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnnuevo, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btneleminartodo, javax.swing.GroupLayout.DEFAULT_SIZE, 106,
Short.MAX_VALUE))))
.addGap(15, 15, 15))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()

22
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnsalir)
.addGap(83, 83, 83))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnagregar)
.addComponent(btnnuevo))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btneleminar)
.addComponent(btneleminartodo))))
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtapellidos, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(1, 1, 1)
.addComponent(btnsalir)
.addGap(3, 3, 3)

23
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(sexo, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 187,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);

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

private void jMenuItem1ActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:
Ventas W1 = new Ventas(); //retorno de boton acceso principal
W1.setVisible(true);
dispose();

private void btnagregarActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here: // botonagregar
String[] agregar = new String[4]; //se crea arreglo de 4 posiciones para capturar datos
sobre las posiciones que se le asignaron
agregar[0] = txtid.getText();
agregar[1] = txtnombre.getText();
agregar[2] = txtapellidos.getText();
agregar[3] = (String) sexo.getSelectedItem();
model.addRow(agregar);

24
private void btnnuevoActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here: //botonnuevo
txtid.setText("");
txtnombre.setText("");
txtapellidos.setText("");

private void btneleminarActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here: //botoneliminar
inteli = tabladedatos.getSelectedRowCount();
if (eli> 0) {
model.removeRow(eli);
} else {
JOptionPane.showMessageDialog(null, "No existen a eliminar");
}
}

private void btneleminartodoActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here: //botoneliminartodo
intelitotal = tabladedatos.getRowCount();
for (inti = elitotal - 1; i>= 0; i--) {
model.removeRow(i);
}
}

private void jMenuItem2ActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:
System.exit(0);
}

private void btnsalirActionPerformed(java.awt.event.ActionEventevt) {


// TODO add your handling code here:

25
Principal W1=new Principal(); //retorno de boton acceso principal
W1.setVisible(true);
dispose();
}

/**
* @paramargs the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and
feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RecursosHumanos.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RecursosHumanos.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RecursosHumanos.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);

26
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RecursosHumanos.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


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

// Variables declaration - do not modify


private javax.swing.JButtonbtnagregar;
private javax.swing.JButtonbtneleminar;
private javax.swing.JButtonbtneleminartodo;
private javax.swing.JButtonbtnnuevo;
private javax.swing.JButtonbtnsalir;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JComboBox<String>sexo;
privatejavax.swing.JTabletabladedatos;
privatejavax.swing.JTextFieldtxtapellidos;
private javax.swing.JTextFieldtxtid;

27
private javax.swing.JTextFieldtxtnombre;
// End of variables declaration
}

Conclusiones

En estas actividades, pude hacer uso de otro método para captura de datos, además de
poder visualizar los datos dentro de un listado, por lo que pude notar es que el hacer uso
de estas interfaces gráficas pones en práctica mucho de los paradigmas de la
programación, pues en este caso hice uso de un arreglo de 4 posiciones con la finalidad
de asignar los datos que vamos capturando cuando el usuario guarda.

En lo personal me doy cuenta que, si no conocer los fundamentos de la programación y


de la orientada a objetos no podremos hacer mucho, ya que una cosa es diseñar la
interfaz gráfica y otro poder instanciar los objetos para que cuando den clic o digiten algo,
pueda responder el código. En general me entusiasma mucho ver como en la siguiente
unidad hacemos la conexión con la base de datos.

28
Bibliografía

1.-David J. Barnes Michael Kölling. (2007). Programación orientada a objetos con Java.
18-02-2020, de Amazonaws.com Sitio web:
https://s3.amazonaws.com/academia.edu.documents/56145172/Programacion_orientada_
a_objetos_con_Java.pdf?response-content-
disposition=inline%3B%20filename%3DProgramacion_orientada_a_objetos_con_Jav.pdf&
X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-
Credential=AKIAIWOWYYGZ2Y53UL3A%2F20190727%2Fus-east-
1%2Fs3%2Faws4_request&X-Amz-Date=20190727T151028Z&X-Amz-Expires=3600&X-
Amz-SignedHeaders=host&X-Amz-
Signature=8e22af485965f9a6b09d87b9f3476bbd7ace714efdefeb83194e78fc49535ea0

2.- P. J. DeitelDeitel& Associates, Inc. H. M. DeitelDeitel& Associates, Inc. (2008). Como


programar en java. 18-02-2020, de PEARS ON EDUCACIÓN, México Sitio web:
http://academica.mx/archivos/blogs/bc579e362adbf2ef27ab2df2a76b43ac/698/Como%20
programar%20en%20Java%20-%207ma%20Edicion%20-%20P.%20J.%20Deitel.pdf

3.- Compuchiqui. (2013). Contenedores En Java - Guardar, Actualizar, Buscar, Eliminar


Registros. 18-02-2020, de YouTube Sitio web:
https://www.youtube.com/watch?v=8Dy2yvlov9A

29

También podría gustarte