事件处理可以简单地这么理解,当有一个事件产生,程序要根据这个事件做出响应。比如,我们做了一个可以通过按钮改变背景颜色的窗口,当我们点击按钮时便产生了一个事件,程序会根据这个事件来做出响应,也就是去改变背景的颜色。
运行结果
那么程序是怎样做出响应的呢?这就需要事件监听器ActionListener,这是一个接口,里面包含了actionPerformed方法(也就是根据事件去执行的操作),所以我们要实现这个接口(实现接口里的actionPerformed方法)做出一个监听器对象出来,并且用按钮来注册这个监听器对象,这样当按钮被点击的时候,就会调用这个监听器来执行响应了。
事件处理机制
代码(第42行开始为实现接口):
1 package buttonPanel; 2 3 import java.awt.*; 4 import java.awt.event.*; //事件监听器接口ActionListener的位置。 5 import javax.swing.*; 6 7 public class ButtonFrame extends JFrame { 8 private ButtonPanel buttonPanel; 9 private static final int DEFAULT_WIDTH = 300; 10 private static final int DEFAULT_HEIGHT = 200; 11 12 public ButtonFrame() { 13 setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); 14 setLocationByPlatform(true); 15 16 //构造按钮 17 JButton redButton = new JButton("RED"); 18 JButton yellowButton = new JButton("YELLOW"); 19 JButton blueButton = new JButton("BLUE"); 20 21 buttonPanel = new ButtonPanel(); 22 23 //添加按钮到面板 24 buttonPanel.add(redButton); 25 buttonPanel.add(yellowButton); 26 buttonPanel.add(blueButton); 27 28 add(buttonPanel); 29 30 //构造对应颜色的动作监听器 31 ColorAction redAction = new ColorAction(Color.red); 32 ColorAction yellowAction = new ColorAction(Color.yellow); 33 ColorAction blueAction = new ColorAction(Color.blue); 34 35 //每个按钮注册对应的监听器 36 redButton.addActionListener(redAction); 37 yellowButton.addActionListener(yellowAction); 38 blueButton.addActionListener(blueAction); 39 } 40 41 //为了方便调用buttonPanel,将ColorAction作为ButtonFrame的内部类。 42 private class ColorAction implements ActionListener { 43 private Color backgroundColor; 44 public ColorAction(Color c) { 45 backgroundColor = c; 46 } 47 public void actionPerformed(ActionEvent event) { 48 buttonPanel.setBackground(backgroundColor); 49 } 50 } 51 52 public static void main(String[] args) { 53 EventQueue.invokeLater(new Runnable() { 54 public void run() { 55 JFrame frame = new ButtonFrame(); 56 frame.setTitle("ColorButton"); 57 frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 58 frame.setVisible(true); 59 } 60 }); 61 } 62 } 63 64 class ButtonPanel extends JPanel { 65 private static final int DEFAUT_WIDTH = 300; 66 private static final int DEFAUT_HEIGHT = 200; 67 68 @Override 69 protected void paintComponent(Graphics g) { 70 g.create(); 71 super.paintComponent(g); 72 } 73 74 @Override 75 public Dimension getPreferredSize() { 76 return new Dimension(DEFAUT_WIDTH,DEFAUT_HEIGHT); 77 } 78 }