监听器
ActionListener接口 ——通常用自己创建的新类implements接口
建议使用匿名内部类实现,因为内部类可以访问类内的变量,而匿名类可以大大简化代码,不需要构造函数。
实例:处理按钮点击事件
1 package button; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * A frame with a button panel 9 */ 10 public class ButtonFrame extends JFrame 11 { 12 private JPanel buttonPanel; 13 private static final int DEFAULT_WIDTH = 300; 14 private static final int DEFAULT_HEIGHT = 200; 15 16 public ButtonFrame() 17 { 18 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 19 20 // create buttons 21 JButton yellowButton = new JButton("Yellow"); 22 JButton blueButton = new JButton("Blue"); 23 JButton redButton = new JButton("Red"); 24 25 buttonPanel = new JPanel(); 26 27 // add buttons to panel 28 buttonPanel.add(yellowButton); 29 buttonPanel.add(blueButton); 30 buttonPanel.add(redButton); 31 32 // add panel to frame 33 add(buttonPanel); 34 35 // create button actions 36 ColorAction yellowAction = new ColorAction(Color.YELLOW); 37 ColorAction blueAction = new ColorAction(Color.BLUE); 38 ColorAction redAction = new ColorAction(Color.RED); 39 40 // associate actions with buttons 41 yellowButton.addActionListener(yellowAction); 42 blueButton.addActionListener(blueAction); 43 redButton.addActionListener(redAction); 44 } 45 46 /** 47 * An action listener that sets the panel's background color. 48 */ 49 private class ColorAction implements ActionListener 50 { 51 private Color backgroundColor; 52 53 public ColorAction(Color c) 54 { 55 backgroundColor = c; 56 } 57 58 public void actionPerformed(ActionEvent event) 59 { 60 buttonPanel.setBackground(backgroundColor); 61 } 62 } 63 }