Sei sulla pagina 1di 14

Programacin en Java

Programacin visual II.

Tarea N 4

Uladech
Universidad Catlica los ngeles de Chimbote Facultad de Ingeniera de Sistemas Departamento Acadmico de Ingeniera de Sistemas

Materia:

Programacin Visual II

Nombre del Profesor:

Ing. Aldo Segismundo Pereda Castillo

Nombre del estudiante:

Alex Ancajima Castro

Grupo: A

No. Cdigo Universitario: 1209110060

Tema del trabajo: Ejercicios de Aplicacin.

Piura, Junio, 2012

Programacin Visual II

Uladech
Desarrollar: 1. En base a lo desarrollado en la pregunta 2 de la tarea anterior (Tarea 3), en lugar de usar objetos JInternalFrame, usar objetos JDialog. package ejemplos_visualii; //IMPORTTAR LOS PAQUETES NECESARIOS: import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.event.*; //CLASE BASE: public class MenuJDialog extends JFrame implements ActionListener{ //CREAR VARIABLES MIEMBROS DE LA CLASE, LA CUAL SE //UTILIZARAN EN ESTA: private JLabel label1,label2,lblm; private JButton boton1, boton2,boton3; private JDesktopPane escritorio; private JTextField cuadro1,cuadro2; private JDialog dialog1, dialog2,dialog3; private JMenuItem item1,item2,item3,item4,item5; //METODO CONSRTRCUTOR EL CUAL CREA EL MENU: public MenuJDialog(){ super("Ejemplo de JDialog"); this.setSize(500, 500); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); escritorio =new JDesktopPane(); this.getContentPane().add(escritorio); //CREACION DE LA BARRA DE MENU: LA CUAL CONTENDR LOS //MENUS; JMenuBar barramenu=new JMenuBar(); barramenu.setBackground(Color.BLACK); JMenu menu1=new JMenu("Ejemplo_JDialog"); JMenu menu2=new JMenu("Operacion"); //CREANDO LOS ITEM DE LOS MENUS: item1=new JMenuItem("JDialog1"); item1.addActionListener(this); item2=new JMenuItem("JDialog2"); item2.addActionListener(this); item3=new JMenuItem("JDialog3"); item3.addActionListener(this); item4=new JMenuItem("salir"); item4.addActionListener(this); item5=new JMenuItem("Acerca de.."); item5.addActionListener(this); menu1.setForeground(Color.WHITE); menu2.setForeground(Color.WHITE); // AGREGANDO LOS ITEMS AL MENU Y LUEGO LOS MENUS A LA //BARRA:

Programacin Visual II

Uladech
menu1.add(item1); menu1.add(item2); menu1.add(item3); menu2.add(item4); menu2.add(item5); barramenu.add(menu1); barramenu.add(menu2); this.setJMenuBar(barramenu); //*********************************************************** this.setVisible(true); } //========================================================== //===== public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); //CREAR UN OBJETO DE LA CLASE ManuJDialog; MenuJDialog menu=new MenuJDialog(); } //========================================================== //======== public void actionPerformed(ActionEvent e){ int a = 0,b = 0,r; JPanel panel=new JPanel(); if(e.getSource()==item1){ contenido1(panel); dialog1 =new JDialog(this,"Ejemplo de una suma"); dialog1.getContentPane().add(panel); dialog1.setBounds(60,100, 300, 200); dialog1.setVisible(true); } else if (e.getSource() == item2) { contenido2(panel); dialog2 =new JDialog(this,"Ejemplo de una resta"); dialog2.getContentPane().add(panel); dialog2.setBounds(60,100, 300, 200); dialog2.setVisible(true); } else if (e.getSource() == item3) { contenido3(panel); dialog3 =new JDialog(this,"Ejemplo de una multiplicacin"); dialog3.getContentPane().add(panel); dialog3.setBounds(60,100, 300, 200); dialog3.setVisible(true); } else if(e.getSource()==item4){ System.exit(0); }

Programacin Visual II

Uladech
else if(e.getSource()==item5){ String texto = "-Programa:\n" + "Ejemplos de JDialog.\n\n" + "-Asignatura:\n" + "Laboratorio II.\n" + "Programacion Visual II.\n\n" + "-Tutor:\n" + "Ing. Aldo S. Pereda C.\n\n" + "-Alumno:\n" + "Ancajima Castro Alex.\n\n" + "Semestre: IV\n\n"; JOptionPane.showMessageDialog(this, texto, "Informacion", JOptionPane.INFORMATION_MESSAGE); } //***********************SELECCION DE //BOTONES********************************** try{ if(e.getSource()==boton1) { a=Integer.parseInt(cuadro1.getText()); b=Integer.parseInt(cuadro2.getText()); r=a+b; lblm.setText(String.valueOf(r)); lblm.setForeground(Color.BLUE); } else if(e.getSource() == boton2) { a=Integer.parseInt(cuadro1.getText()); b=Integer.parseInt(cuadro2.getText()); r=a-b; lblm.setText(String.valueOf(r)); lblm.setForeground(Color.BLUE); } else if(e.getSource() == boton3) { a=Integer.parseInt(cuadro1.getText()); b=Integer.parseInt(cuadro2.getText()); r=a*b; lblm.setText(String.valueOf(r)); lblm.setForeground(Color.BLUE); } } catch(Exception er){ JOptionPane.showMessageDialog(this,"los datos no son los correctos.\n" + "O le faltan datos\n" + "Por favor VERIFIQUE!","Mensaje de error!",JOptionPane.ERROR_MESSAGE); }

Programacin Visual II

Uladech
} //+*******************CREANDO EL CONTENIDO DE LOS //JDIALOG***************** //-PARA CADA UNO DE LOS JDIALOG: public void contenido1(JPanel panel){ panel.setLayout(new FlowLayout()); label1 =new JLabel("Ingrese el 1Numero",SwingConstants.CENTER); panel.add(label1); cuadro1 =new JTextField(10); panel.add(cuadro1); label2 =new JLabel("Ingrese el 2Numero",SwingConstants.CENTER); panel.add(label2); cuadro2 =new JTextField(10); panel.add(cuadro2); boton1 =new JButton("Calcular"); boton1.addActionListener(this); panel.add(boton1); lblm =new JLabel("Aqui se ovserbar la respuesta",SwingConstants.CENTER); lblm.setForeground(Color.ORANGE); panel.add(lblm); panel.setBounds(30,30,45,30); } public void contenido2(JPanel panel){ panel.setLayout(new FlowLayout()); label1 =new JLabel("Ingrese el 1Numero",SwingConstants.CENTER); panel.add(label1); cuadro1 =new JTextField(10); panel.add(cuadro1); label2 =new JLabel("Ingrese el 2Numero",SwingConstants.CENTER); panel.add(label2); cuadro2 =new JTextField(10); panel.add(cuadro2); boton2 =new JButton("Calcular"); boton2.addActionListener(this); panel.add(boton2); lblm =new JLabel("Aqui se ovserbar la respuesta",SwingConstants.CENTER); lblm.setForeground(Color.darkGray); panel.add(lblm); panel.setBounds(30,30,45,30); } public void contenido3(JPanel panel){

Programacin Visual II

Uladech
panel.setLayout(new FlowLayout()); label1 =new JLabel("Ingrese el 1Numero",SwingConstants.CENTER); panel.add(label1); cuadro1 =new JTextField(10); panel.add(cuadro1); label2 =new JLabel("Ingrese el 2Numero",SwingConstants.CENTER); panel.add(label2); cuadro2 =new JTextField(10); panel.add(cuadro2); boton3 =new JButton("Calcular"); boton3.addActionListener(this); panel.add(boton3); lblm =new JLabel("Aqui se ovserbar la respuesta",SwingConstants.CENTER); lblm.setForeground(Color.GREEN); panel.add(lblm); panel.setBounds(30,30,45,30); } }

Programacin Visual II

Uladech
2. Construye un arbol, usando Jtree, indicando en el nodo principal Ingeniera de Sistemas. Dentro de ste nodo crear nodos hijos de aquellos ciclos que ests llevando cursos. Finalmente de ltimos nodos hijos crear en cada uno nodos indicando el nombre del curso que estas llevando actualmente. package ejemplos_visualii; import javax.swing.*; import java.awt.*; import javax.swing.event.*; import java.awt.event.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; public class JTree_Sistemas { public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); //CONTRUCCION DE UN ARBOL: DefaultMutableTreeNode sistemas=new DefaultMutableTreeNode("Ing.Sistemas"); //DefaulttreeModel: contiene los datos del arbol //en este caso, modelo va a contener los datos del arbol creado DefaultTreeModel modelo=new DefaultTreeModel(sistemas); //creamos un arbol, la cual enviamos como parametro el modelo("DATOS"): JTree arbol=new JTree(modelo); //CONSTRUCION DE LOS DATOS DEL ARBOL: DefaultMutableTreeNode cicloI=new DefaultMutableTreeNode("cicloI"); DefaultMutableTreeNode cicloII=new DefaultMutableTreeNode("cicloII"); DefaultMutableTreeNode cicloIII=new DefaultMutableTreeNode("cicloIII"); DefaultMutableTreeNode cicloIV=new DefaultMutableTreeNode("cicloIV"); modelo.insertNodeInto( cicloI,sistemas,0); modelo.insertNodeInto(cicloII,sistemas, 1); modelo.insertNodeInto(cicloIII,sistemas, 2); modelo.insertNodeInto(cicloIV,sistemas, 3); //PRIMER CICLO DefaultMutableTreeNode Introduccion=new DefaultMutableTreeNode("Introduccion a la Ing."); DefaultMutableTreeNode Algoritmos=new DefaultMutableTreeNode("Algoritmos"); DefaultMutableTreeNode Matematica=new DefaultMutableTreeNode("Matematica"); DefaultMutableTreeNode Calculo=new DefaultMutableTreeNode("Calculo Diferencial"); DefaultMutableTreeNode Comuni=new DefaultMutableTreeNode("Comunicacion"); DefaultMutableTreeNode MedioA=new DefaultMutableTreeNode("Medio Ambiente"); DefaultMutableTreeNode Derechos=new DefaultMutableTreeNode("Derechos Humanos"); modelo.insertNodeInto(Introduccion, cicloI,0); modelo.insertNodeInto(Algoritmos, cicloI, 1);

Programacin Visual II

Uladech
modelo.insertNodeInto(Matematica, cicloI, 2); modelo.insertNodeInto(Calculo, cicloI, 3); modelo.insertNodeInto(Comuni, cicloI, 4); modelo.insertNodeInto(MedioA, cicloI, 5); modelo.insertNodeInto(Derechos, cicloI, 6); //SEGUNDO CICLO: DefaultMutableTreeNode Desa=new DefaultMutableTreeNode("Desarrollo de Aplicaciones M."); DefaultMutableTreeNode Tecnica=new DefaultMutableTreeNode("Tecnicas de Programacion"); DefaultMutableTreeNode Fisica=new DefaultMutableTreeNode("Fisica I"); DefaultMutableTreeNode Deonto=new DefaultMutableTreeNode("Deontologia"); DefaultMutableTreeNode Estadis=new DefaultMutableTreeNode("Estadistica"); DefaultMutableTreeNode Practicas=new DefaultMutableTreeNode("Practicas Operativas Justas"); DefaultMutableTreeNode Vida=new DefaultMutableTreeNode("Vida Espiritual"); modelo.insertNodeInto(Desa, cicloII,0); modelo.insertNodeInto(Tecnica, cicloII, 1); modelo.insertNodeInto(Deonto, cicloII, 2); modelo.insertNodeInto(Estadis, cicloII, 3); modelo.insertNodeInto(Practicas, cicloII, 4); modelo.insertNodeInto(Vida, cicloII, 5); modelo.insertNodeInto(Fisica, cicloII, 6); //TERCE CICLO: DefaultMutableTreeNode Logica=new DefaultMutableTreeNode("logica Digital."); DefaultMutableTreeNode Conta=new DefaultMutableTreeNode("Contabilidad"); DefaultMutableTreeNode VisualI=new DefaultMutableTreeNode("Programacion Visual II"); DefaultMutableTreeNode Lenguaje=new DefaultMutableTreeNode("Lenguaje Estructurado de Consulta"); DefaultMutableTreeNode Estructura=new DefaultMutableTreeNode("Estructura de Datos"); DefaultMutableTreeNode FisicaII=new DefaultMutableTreeNode("Fisica II"); DefaultMutableTreeNode Asuntos=new DefaultMutableTreeNode("Asuntos Consumidores"); modelo.insertNodeInto(Logica, cicloIII,0); modelo.insertNodeInto(Conta, cicloIII, 1); modelo.insertNodeInto(VisualI, cicloIII, 2); modelo.insertNodeInto(Lenguaje, cicloIII, 3); modelo.insertNodeInto(Estructura, cicloIII, 4); modelo.insertNodeInto(FisicaII, cicloIII, 5); modelo.insertNodeInto(Asuntos, cicloIII, 6); //CUARTO CICLO: DefaultMutableTreeNode Admi=new DefaultMutableTreeNode("Administracion de Empresas"); DefaultMutableTreeNode Costos=new DefaultMutableTreeNode("Costos y Presupuestos");

Programacin Visual II

Uladech
DefaultMutableTreeNode VisualII=new DefaultMutableTreeNode("Programacion Visual II"); DefaultMutableTreeNode Mate=new DefaultMutableTreeNode("Matematica Discreta C."); DefaultMutableTreeNode Base=new DefaultMutableTreeNode("Base de Datos"); DefaultMutableTreeNode Gobernanzas=new DefaultMutableTreeNode("Gobernanzas de las Organizaciones"); modelo.insertNodeInto(Admi, cicloIV,0); modelo.insertNodeInto(Costos, cicloIV, 1); modelo.insertNodeInto(VisualII, cicloIV, 2); modelo.insertNodeInto(Mate, cicloIV, 3); modelo.insertNodeInto(Base, cicloIV, 4); modelo.insertNodeInto(Gobernanzas, cicloIV, 5); //CONSTRUCCION Y VISUALICION DE LA VENTANA: JFrame v=new JFrame("Presentacion de cursos mediante un arbol"); v.setSize(400,700); v.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JScrollPane scroll=new JScrollPane(arbol); v.add(scroll); JButton b=new JButton("hola"); v.getContentPane().add(scroll); v.setVisible(true); } }

Programacin Visual II

Uladech
3.

Construye una aplicacin que hagas uso de JFormattedTextField y a partir de una instigacin tuya validar cuadros de textos que muestre los datos en maysculas y algn dato que indique fecha. Puedes hacer uso de datos numricos en los cuadros de textos.

package ejemplos_visualii; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.text.MaskFormatter; public class Ejemplo2_JFormattedTextField extends JFrame implements ActionListener{ JFormattedTextField dni,fecha; JLabel dnil,fechal,nombrel,apellidol,men; JTextField nombre,apellido; JButton ingresar,salir,cancelar; public Ejemplo2_JFormattedTextField(){ super("EJEMPLO DE JFORMATTEDTEXTFIELD"); this.setSize(200,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel=new JPanel(); try{ //indicamos en el formato del DNI, que aparte del numero, //se tiene que escribir una letra como identificacion //la cual sera transformada en mayuscula: MaskFormatter formatdni=new MaskFormatter("########-U"); MaskFormatter formatfecha=new MaskFormatter("##/##/####"); //=================================================== nombrel =new JLabel("Nombre",SwingConstants.CENTER); panel.add(nombrel); nombre =new JTextField(10); panel.add(nombre); apellidol =new JLabel("Apellidos", SwingConstants.CENTER); panel.add(apellidol); apellido =new JTextField(10); panel.add(apellido); dnil =new JLabel("DNI",SwingConstants.CENTER); panel.add(dnil); dni =new JFormattedTextField(formatdni); panel.add(dni); //enviando formato a travez de un label: como //ejemplo: JLabel forn=new JLabel("Formato: Num / Cantidad=8",SwingConstants.CENTER); panel.add(forn); fechal =new JLabel("-----------Fecha-------:",SwingConstants.CENTER); panel.add(fechal); fecha =new JFormattedTextField(formatfecha); fecha.setValue("00/00/0000"); JSeparator separador=new JSeparator(); separador.setBackground(Color.red);

Programacin Visual II

Uladech
panel.add(fecha); JLabel forf=new JLabel("Formato:dd/mm/yyyy",SwingConstants.CENTER); panel.add(forf); panel.add(separador); ingresar =new JButton("Verificar"); ingresar.addActionListener(this); panel.add(ingresar); salir =new JButton("Salir"); salir.addActionListener(this); panel.add(salir); cancelar =new JButton("Cancelar"); cancelar.addActionListener(this); panel.add(cancelar); men =new JLabel("--------mensaje------"); panel.add(men); //================================================================================ ===== } catch(Exception e){ System.out.println("Error!"+e.getMessage()); } //================================================================================ == this.add(panel); this.setVisible(true); } //METODO PRIMCIPAL public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); Ejemplo2_JFormattedTextField objformat=new Ejemplo2_JFormattedTextField(); //validardni vf=new validardni(); } //================================================================================ public void actionPerformed(ActionEvent e){ if(e.getSource()==ingresar){ try{ validardni vf=new validardni(); if(vf.verify(dni)==false){ men.setText("Los datos son correctos"); men.setForeground(Color.BLUE); } else{ men.setText("Los datos no son correctos"); men.setForeground(Color.red);} } catch(Exception err){} } else if(e.getSource()==cancelar){ nombre.setText("");

Programacin Visual II

Uladech
apellido.setText(""); dni.setText(""); fecha.setText(""); men.setText("Los datos se han limpiado"); men.setForeground(Color.GREEN); } else if(e.getSource()==salir){ dispose(); } } //==================================================================== static class validardni extends InputVerifier{ String pattern = "RWAGMYFPDXBNJZSQVHLCKET"; /** * Verifica un DNI. */ private boolean verifyDNI(String dni) { // Eliminamos caracteres de separacin. dni = dni.replaceAll("[.-]", ""); if (dni.length() != 9) { return false; } // El ltimo carcter debe ser una letra // if (!Character.isLetter(dni.charAt(8))) { // return false; //} int digits; try { digits = Integer.parseInt(dni.substring(0, 8)); } catch (NumberFormatException e) { return false; } // El algoritmo mgico int pos = (digits%23); if (pos == 0) { pos = pattern.length(); } pos = pos -1; // Las tiras en Java estn basadas en cero! return (pattern.charAt(pos) == dni.charAt(8)); } /** * Sobrescribimos el mtodo del padre para realizar la * comprobacin del DNI entrado. */ public boolean verify(JComponent input) { if (input instanceof JFormattedTextField) { Object o = ((JFormattedTextField)input).getValue(); if (o == null) return true; String value = o.toString(); return verifyDNI(value); }

Programacin Visual II

Uladech
return false; } //==============================================================

} } Este programa verifica si el DNI ingresado tiene el formato correcto, si no lo tiene muestra un mensaje los datos no son los correctos, el formato correcto es el numero de DNI completo mas una letra, la cual esta separada por un guion y convertida en mayscula.

Programacin Visual II

Potrebbero piacerti anche