1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InnerExample {
/**
* @param args
*/
public static void main(String[] args) {
JFrame myFrame = new JFrame();
myFrame.setTitle("test");
JButton bouton = new JButton("Test");
myFrame.getContentPane().add(bouton);
myFrame.setSize(100,50);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// on déclare une classe anonyme qui implémente l'interface ActionListener
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bonjour");
}
};
bouton.addActionListener(al);
// on déclare une classe Locale, qui implémente ActionListener, mais qui a aussi un constructeur
// explicite et un nom
class MyListener implements ActionListener{
String text;
public MyListener(String text){
this.text=text;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(text);
}
}
// on l'instancie tant qu'on veux
bouton.addActionListener(new MyListener("test 1"));
bouton.addActionListener(new MyListener("test 2"));
bouton.addActionListener(new MyListener("test 3"));
myFrame.setVisible(true);
}
} |
Partager