martes, 31 de julio de 2007

Listeners

La plataforma Swing se basa primordialmente para el manejo de eventos en el concepto de escucha o Listener; la teoría general establece que existe un objeto al que llamaremos disparador que realiza alguna acción sobre otro objeto reactivo. El objeto entonces informa a varios Listener de que algo ha ocurrido en el disparador. Entonces cada uno de los listeners puede realizar alguna acción en base al evento que ocurrió.

La metáfora que utilizaremos para comprender el concepto es mas o menos el siguiente: Imagina que tenemos un sistema que mide la temperatura del ambiente, este sistema puede conectarse con multiples sistemas independientes; imaginemos entonces que podemos conectar un aparato que pite cada que la temperatura rebase cierto limite, además podemos conectar otro aparato que actualize la temperatura en un sitio Web cada que esta cambie, y podemos conectar más aparatos que realizen funciones diferentes, siempre y cuando sean capaces de saber cuando la temperatura cambia.

Entre los componentes Swing hay una amplia gama de Listener's que se implementan como Interfaces, si queremos que determinada clase responda a los eventos de un objeto es necesario que este implemente la interface Listener adecuada y que se registre con el objeto que genera los reportes de evento. El ejemplo más sencillo es el de los botones comunes y la interfaz ActionListener.


JButton boton = new JButton("El boton");

//ActionListener es la clase encargada de escuchar eventos de acción
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Se ha hecho click en el botón");
}
}

boton.addActionListener(al);

//Registramos el nuevo objeto como escucha del botón
JButton boton2 = new JButton("Otro boton");
//Podemos agregar un Listener a varios elementos
boton2.addActionListener(al);
//E igualmente podemos registrar mas de un listener por objeto
boton.addActionListener(otro_listener);

//Borramos el registro de escucha cuando deja de interesarnos
boton.removeActionListener(al);


Algunos elementos pueden llegar a tener multiples interfaces para utilizar Listeners, como el caso de los JFrame's, que permiten recibir WindowListener, FrameListener, PropertyChangeListener, MouseListener, MouseMotionListener entre otros. En la documentación de Java pueden encontrarse bastantes referencias a los listeners que acepta cada uno de los componente Swing.

Existen casos de Listeners que declaran muchos métodos, como el caso del WindowListener que implementa windowClosed, windowClosing, windowIconofied, y otros muchos, estos métodos deben cubrirse completamente en cualquier clase que implemente la interfaz, pero para facilitar las cosas por cada una de estas clases existe una clase Adapter que implementa una funcionalidad vacia en todos estos métodos.


//Usando el adapter nos evitamos escribir todos los métodos
WindowListener wl = new WindowAdapter() {
public void windowClosed(WindowEvent we) {
System.out.println("Se cerro la ventana");
}
}

9 comentarios:

Anónimo dijo...

Más de los mismo, "pirata" pon algo nuevo... eso es muy redundate en internet uno lo encuentra donde sea.

Y sobre todo que sea tuyo.

Atte.
Programador Neurotico.

Gonza dijo...

Soy re novato así que me sirvió, bien explicado!

Unknown dijo...

nesesito aplicar la accion de mover una linea con el mause.. con esto como podria agregarlo en mi codigo.. sk pongo coordenadas en x1,y1,x2,y2 y de la linea q se dibuja nesesito poder moverlo con el mause hacia cualkier ladoo.. nesesito ayuda!!

Anónimo dijo...

Precisely what everyone else engages in with regards to swimwear and consequently the things you will need to try and do different. [url=http://ladies-swimwear.webnode.com/]brazilian swimwear[/url] Supplies and developing throughout Chicago -- swimwear will leave without adios [url=http://fantasie-swimwear.webnode.com/]panache swimwear[/url] The supreme magic formula for swimwear you are able to educate yourself about as we speak. [url=http://push-up-swimwear.webnode.com/]lands end swimwear[/url] Hard to find study will give you the run information over bikini which experts state just one or two buyers know. [url=http://designer-swimwear.webnode.com/]vitamin swimwear[/url] Smart techniques for swimwear which you can use starting immediately. [url=http://beach-swimwear.webnode.com/]cheap swimwear[/url]
The key reason why most are extremely wrong over bikini and as a result reasons why you must look at this ebook. [url=http://discount-swimwear.webnode.com/]discount swimwear[/url] The Secret dominate the swimwear-arena Is Very Straightforward! [url=http://spanx-swimwear0.webnode.com/]fantasie swimwear[/url] Honest site presents Couple of completely new things on bikini that noone is speaking about. [url=http://swimwear-sale.webnode.com/]swimwear sale[/url] Figure out who is discussing about swimwear and also reasons why you should feel concerned.[url=http://bikinis1.webnode.com/]bikinis[/url] Why not a single person is discussing about bikini and something that one ought to execute today. [url=http://bikini-beach.webnode.com/]bikini beach[/url]

William Ochoa dijo...

muy bueno, justo estoy buscando temas sobre listeners para programar en android. pasense por mi blog: www.programmerbook.blogspot.com

Anónimo dijo...

Hi, I do believe this is a great web site. I
stumbledupon it ;) I may come back once again since I saved as a favorite it.
Money and freedom is the greatest way to change,
may you be rich and continue to guide other people.

My web blog - credite rapide 2013 ()

Anónimo dijo...

Me gusta http://warez-new.info

Anónimo dijo...

Где скачать бесплатно

yanmaneee dijo...

balenciaga
kyrie irving shoes
hermes birkin bag
jordan 12
air max 90
nike air force
air max 95
yeezy boost
moncler coat
air max 95