Grácias al diseño de los oyentes se puede hacer que se vayan añadiendo y superponiendo eventos dinámicamente Mira este ejemplo:
// EventosDinamicos.java
// Se puede cambiar el comportamineto de los eventos dinamicamente
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import net.juantxu.swing.*;
public class EventosDinamicos extends JApplet{
ArrayList v = new ArrayList();
int i = 0;
JButton
boton1 = new JButton("boton 1"),
boton2 = new JButton("boton 2");
JTextArea txt = new JTextArea();
class B implements ActionListener{
public void actionPerformed(ActionEvent e){
txt.append("se ha presionado un boton\n");
}
}
class ContadorOyente implements ActionListener{
int indice;
// el constructor
public ContadorOyente(int i){
indice = i;
}
public void actionPerformed(ActionEvent e){
txt.append("Oyentes contados : " + indice + "\n");
}
}
class B1 implements ActionListener{
public void actionPerformed(ActionEvent e){
txt.append("Botón 1 pulsado\n");
ActionListener a = new ContadorOyente(i++);
v.add(a);
boton2.addActionListener(a); // fijate que le añadimos el array!!
}
}
class B2 implements ActionListener{
public void actionPerformed(ActionEvent e){
txt.append("boton 2 pulsado\n");
int fin = v.size() -1;
if (fin >= 0){ // si pico en el boton dos quito el último oyente del boton
boton2.removeActionListener( (ActionListener)v.get(fin) );
v.remove(fin); // y de la lista
}
}
}
public void init(){
Container cp = getContentPane();
boton1.addActionListener(new B() );
boton1.addActionListener(new B1() );
boton2.addActionListener(new B() );
boton2.addActionListener(new B2() );
JPanel p = new JPanel();
p.add(boton1);
p.add(boton2);
cp.add(BorderLayout.NORTH, p);
cp.add( new JScrollPane(txt) );
}
// para poder ejecutarlo desde consola
// por eso he incluido net.juantxu.swing
public static void main(String[] args){
Console.run(new EventosDinamicos(), 250, 300);
}
}
y aqui tienes como queda