elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Trabajando con las ramas de git (tercera parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  como crear formularios
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: como crear formularios  (Leído 4,605 veces)
sapito169


Desconectado Desconectado

Mensajes: 628



Ver Perfil
como crear formularios
« en: 11 Diciembre 2011, 03:20 am »

Esta vez voy hablar con evidencias
Veamos como un desarrollador normal creando un formulario


Código
  1.  
  2. package com.ejemplo;
  3.  
  4. public class PanFeoContacto extends javax.swing.JPanel {
  5.  
  6.    public PanFeoContacto() {
  7.        initComponents();
  8.    }
  9.  
  10.  
  11.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  12.    private void initComponents() {
  13.  
  14.        jLabel1 = new javax.swing.JLabel();
  15.        jLabel2 = new javax.swing.JLabel();
  16.        jTextField1 = new javax.swing.JTextField();
  17.        jTextField2 = new javax.swing.JTextField();
  18.        jLabel3 = new javax.swing.JLabel();
  19.        jTextField3 = new javax.swing.JTextField();
  20.        jLabel4 = new javax.swing.JLabel();
  21.        jSpinner1 = new javax.swing.JSpinner();
  22.  
  23.        jLabel1.setText("Nombre");
  24.  
  25.        jLabel2.setText("Apellido");
  26.  
  27.        jLabel3.setText("Direcion");
  28.  
  29.        jLabel4.setText("Edad");
  30.  
  31.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
  32.        this.setLayout(layout);
  33.        layout.setHorizontalGroup(
  34.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  35.            .addGroup(layout.createSequentialGroup()
  36.                .addContainerGap()
  37.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  38.                    .addGroup(layout.createSequentialGroup()
  39.                        .addComponent(jLabel1)
  40.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  41.                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE))
  42.                    .addGroup(layout.createSequentialGroup()
  43.                        .addComponent(jLabel2)
  44.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  45.                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE))
  46.                    .addGroup(layout.createSequentialGroup()
  47.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  48.                            .addComponent(jLabel3)
  49.                            .addComponent(jLabel4))
  50.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  51.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  52.                            .addComponent(jSpinner1, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
  53.                            .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE))))
  54.                .addContainerGap())
  55.        );
  56.        layout.setVerticalGroup(
  57.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  58.            .addGroup(layout.createSequentialGroup()
  59.                .addContainerGap()
  60.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  61.                    .addComponent(jLabel1)
  62.                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  63.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  64.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  65.                    .addComponent(jLabel2)
  66.                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  67.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  68.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  69.                    .addComponent(jLabel3)
  70.                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  71.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  72.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  73.                    .addComponent(jLabel4)
  74.                    .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  75.                .addContainerGap(191, Short.MAX_VALUE))
  76.        );
  77.    }// </editor-fold>                        
  78.  
  79.  
  80.    // Variables declaration - do not modify                    
  81.    private javax.swing.JLabel jLabel1;
  82.    private javax.swing.JLabel jLabel2;
  83.    private javax.swing.JLabel jLabel3;
  84.    private javax.swing.JLabel jLabel4;
  85.    private javax.swing.JSpinner jSpinner1;
  86.    private javax.swing.JTextField jTextField1;
  87.    private javax.swing.JTextField jTextField2;
  88.    private javax.swing.JTextField jTextField3;
  89.    // End of variables declaration                  
  90.  
  91. }
  92.  
  93.  

todo el código es incomprensible inmantenible difícil de entender de modificar es mas el ide no te permite editar casi la totalidad de código
es mas para modificarlo tienes que usar una serie de pasos en el ide eso de precodigo postcodigo solo funciona con netbeans y require un horrible xml de ayuda que te lo crea el ide solo funciono en netbeans
 estorba si usas eclipse y esto solo es un ejemplo trivial la realidad es que me vi en la desgracia de usar formulario 10 veces más complicados con 10 veces de código con más de 50 componentes con paneles dentro de otro y con diferentes layauts y enzima al estilo wizard para que quepa en la pantalla casi me dieron ganas de renunciar al ver que cada vez que modifica un componente todo se desarmaba desaparecían paneles enteros y solo funcionaba con la paleta
Solo pensar en hacerle refactoring es ciencia ficion


Bueno pues ágamos lo a mano solo usando swing


Código
  1. package com.ejemplo;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Container;
  5. import java.awt.GridBagConstraints;
  6. import java.awt.GridBagLayout;
  7. import java.awt.Insets;
  8. import javax.swing.JLabel;
  9. import javax.swing.JPanel;
  10. import javax.swing.JSpinner;
  11. import javax.swing.JTextField;
  12. import javax.swing.SpinnerNumberModel;
  13.  
  14.  
  15. public class PanelContacto {
  16.  
  17.    private final JPanel panel = new JPanel();
  18.  
  19.  
  20.    public PanelContacto() {
  21.        Insets insets = new Insets(5, 5, 5, 5);
  22.        panel.setLayout(new GridBagLayout());
  23.        panel.add(new JLabel("Nombre"), new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, insets, 0, 0));
  24.        panel.add(new JTextField(), new GridBagConstraints(1, 1, 1, 1, 1, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, insets, 0, 0));
  25.        panel.add(new JLabel("Apellido"), new GridBagConstraints(0, 2, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, insets, 0, 0));
  26.        panel.add(new JTextField(), new GridBagConstraints(1, 2, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, insets, 0, 0));
  27.        panel.add(new JLabel("Direcion"), new GridBagConstraints(0, 3, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, insets, 0, 0));
  28.        panel.add(new JTextField(), new GridBagConstraints(1, 3, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, insets, 0, 0));
  29.        panel.add(new JLabel("Edad"), new GridBagConstraints(0, 4, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, insets, 0, 0));
  30.        panel.add(new JSpinner(new SpinnerNumberModel(1, 1, 100, 1)), new GridBagConstraints(1, 4, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, insets, 0, 0));
  31.  
  32.    }
  33.  
  34.    public Container getPanel() {
  35.        JPanel respuesta = new JPanel();
  36.        respuesta.setLayout(new BorderLayout());
  37.        respuesta.add(panel, BorderLayout.NORTH);
  38.        return respuesta;
  39.    }
  40. }
  41.  
  42.  

Es feo pero es 100 veces mejor que la opción anterior además requiere algunos hacks(los layauts de swing son malos)


Luego de hacer refactoring y usar el patrón de diseño builder + interface fluida

Código
  1. package com.ejemplo;
  2.  
  3.  
  4. import java.awt.Container;
  5. import javax.swing.JSpinner;
  6. import javax.swing.JTextField;
  7. import javax.swing.SpinnerNumberModel;
  8.  
  9. public class PanelConPatronBuilder {
  10.  
  11.    public PanelConPatronBuilder() {
  12.    }
  13.  
  14.    public Container getPanel() {
  15.  
  16.        return new PanelBuilder().agregaFila("Nombre", new JTextField()).
  17.                agregaFila("Apellido", new JTextField()).
  18.                agregaFila("Direcion", new JTextField()).
  19.                agregaFila("Edad", new JSpinner(new SpinnerNumberModel(1, 1, 100, 1))).getPanel();
  20.    }
  21. }
  22.  
  23.  
  24.  

U eso es genial mira el código habla por sí solo pero requiera ayuda de una clase echa en casa que tendrías que mantener y crear en caso de que la pierdas 

Aquí está la clase


Código
  1. package com.ejemplo;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Container;
  5. import java.awt.GridBagConstraints;
  6. import java.awt.GridBagLayout;
  7. import java.awt.Insets;
  8. import javax.swing.JComponent;
  9. import javax.swing.JLabel;
  10. import javax.swing.JPanel;
  11.  
  12. public class PanelBuilder {
  13.  
  14.    private final Container panel=new JPanel();
  15.    private final Insets insets = new Insets(5, 5, 5, 5);
  16.    int cont = -1;
  17.  
  18.    public PanelBuilder() {
  19.  
  20.        panel.setLayout(new GridBagLayout());
  21.    }
  22.  
  23.  
  24.  
  25.  
  26.    public PanelBuilder agregaFila(String nombre,JComponent jTextField) {
  27.        panel.add(new JLabel(nombre), restricionDeEtiqueta(++cont));
  28.        panel.add(jTextField, restricionComponente(cont));
  29.        return  this;
  30.    }
  31.  
  32.    private GridBagConstraints restricionComponente(int cont) {
  33.        return new GridBagConstraints(1, cont, 1, 1, 1, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, insets, 0, 0);
  34.    }
  35.  
  36.    private GridBagConstraints restricionDeEtiqueta(int cont) {
  37.        return new GridBagConstraints(0, cont, 1, 1, 0, 0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, insets, 0, 0);
  38.    }
  39.  
  40.    public Container getPanel() {
  41.        JPanel respuesta = new JPanel();
  42.        respuesta.setLayout(new BorderLayout());
  43.        respuesta.add(panel, BorderLayout.NORTH);
  44.        return respuesta;
  45.    }
  46. }
  47.  


Ahora si es enserio usando la ayuda de un librería externa bien echa

package com.ejemplo;

import java.awt.Container;
import org.metawidget.swing.SwingMetawidget;
Código
  1. public class PanelContactoMetaWidtget {
  2.  
  3.    public Container getPanel() {
  4.        SwingMetawidget swingMetawidget =new SwingMetawidget();
  5.        swingMetawidget.setToInspect(new Contacto());
  6.        return swingMetawidget;
  7.    }
  8. }
  9.  

Y requiere un pojo de toda la vida
package com.ejemplo;

Código
  1. public class Contacto {
  2.  
  3.    private String nombre;
  4.    private String apellido;
  5.    private String direcion;
  6.    private int edad;
  7.  
  8.    public String getNombre() {
  9.        return nombre;
  10.    }
  11.  
  12.    public void setNombre(String nombre) {
  13.        this.nombre = nombre;
  14.    }
  15.  
  16.    public String getApellido() {
  17.        return apellido;
  18.    }
  19.  
  20.    public void setApellido(String apellido) {
  21.        this.apellido = apellido;
  22.    }
  23.  
  24.    public String getDirecion() {
  25.        return direcion;
  26.    }
  27.  
  28.  
  29. public void setDirecion(String direcion) {
  30.        this.direcion = direcion;
  31.    }
  32.  
  33.    public int getEdad() {
  34.        return edad;
  35.    }
  36.  
  37.    public void setEdad(int edad) {
  38.        this.edad = edad;
  39.  
  40.    }
  41. }
  42.  
y esta librería te obliga a programar orientado a objetos lo cual es bueno porque en un proyecto grande igual tendrías todo partido en varias clases pongámonos esta clase librería te pide que crees la clase contacto que es un pojo que lo arias de toda maneras en caso de que el contacto cambie automáticamente la vista se actualizaría
Digamos que tienes 100 paneles de contacto en caso de que cambie el contacto solo modificarías la clase contacto


metawidget http://metawidget.org/
builder http://architects.dzone.com/news/factories-builders-and-fluent-








En línea

kasiko

Desconectado Desconectado

Mensajes: 218



Ver Perfil
Re: como crear formularios
« Respuesta #1 en: 12 Diciembre 2011, 18:06 pm »

muy bueno  ::)


En línea

Nos vemos...

Proteus1989

Desconectado Desconectado

Mensajes: 184



Ver Perfil WWW
Re: como crear formularios
« Respuesta #2 en: 12 Diciembre 2011, 18:54 pm »

 ;) Genial tuto
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[php&mysql]crear query sql mediante formularios
Bases de Datos
twoz 3 7,431 Último mensaje 9 Marzo 2009, 06:42 am
por ^Tifa^
Es posible crear nuevos iconos para los formularios... Como...??? « 1 2 »
Programación Visual Basic
angelcont22 15 10,225 Último mensaje 29 Agosto 2009, 05:27 am
por agus0
Como completar formularios web y enviarlos.
.NET (C#, VB.NET, ASP)
agus0 2 5,721 Último mensaje 24 Octubre 2009, 22:13 pm
por agus0
Crear Un Bot Que Autocomplete Formularios Web (SWF)
Programación Visual Basic
agus0 2 4,577 Último mensaje 28 Octubre 2010, 15:14 pm
por aaronduran2
[IMPRESIONANTE] Crear Formularios en VBS!
Scripting
79137913 9 21,258 Último mensaje 21 Abril 2014, 09:21 am
por hostbob
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines