Table of contents
1. The concept of events
In some interfaces we wrote earlier, clicking the button did not have the effect we wanted, because we did not add so-called events to it. So what exactly is an event? An event is when a certain operation occurs on a component, it will automatically trigger the execution of a piece of code
2. Event mechanism
低级事件 ComponentEvent 组件事件,当组件尺寸发生变化,位置移动。 显示/隐藏状态发生改变时触发该事件 ContainerEvent 容器事件。当容器1里发生添加组件,删除组件 时触发该事件 WindowEvent 窗口事件,当窗口状态发生改变(如打开,关 闭,最大化,最小化)时触发该事件 FocusEvent 焦点事件,当组件得到焦点或失去焦点时触发 该事件 KeyEvent 键盘事件,当键盘被按下,松开,单击时触发 该事件 MouseEvent 鼠标事件,当进行单击,按下,松开,移动鼠 标等动作时触发该事件 PaintEvent 组件绘制事件,该事件是一个特殊的事件类型 ,当GUI组件调用update/paint方法来呈现自身 时触发该事件,该事件并非专用于事件处理模 型 高级事件 ActionEvent 动作事件,当按钮,菜单项被单击,在TextField中 按Enter键时触发 Ajustment 调节事件,在滑动条上移动滑块以调节数值触发该 事件 ItemEvent 选项事件,当用户选中某项,或取消选中某项时触 发该事件 TextEvent 文本事件,当文本框,文本域里的文本发生改变时 触发该事件 事件监听器 不同的事件需要使用不同的监听器监听,不同的监听器需要实现不同的监听器接口,当指定事件发生后,事件监听器就会调用所包含的事件处理器(实例方法)来处理事件 事件类别 描述信息 监听器接口名 ActionEvent 激活组件 ActionListener ItemEvent 选择了某些项目 ItemListener MouseEvent 鼠标移动 MouseMotionListener MouseEvent 鼠标点击等 MouseListener KeyEvent 键盘输入 KeyListener FocusEvent 组件收到或失去焦点 FocusListener AdjustmentEvent 移动了滚动条等组件 AdjustmentListener ComponentEvent 对象移动缩放显示隐藏等 ComponentListener WindowEvent 窗口收到窗口级事件 WindowListener ContainerEvent 容器中增加删除了组件 ContainerListener TextEvent 文本字段或文本去除发生改变 TextListener
Here we can add events using anonymous inner classes or outer class methods, but I prefer inner classes, which are more convenient, after all, most of them are only used once.
(1) Case 1
Requirement: Click OK to display the statement in the text
public static void main(String[] args) { Frame s=new Frame("标题"); TextField tf=new TextField(30); Button bt=new Button("确定"); s.add(tf,BorderLayout.NORTH); s.add(bt); bt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tf.setText("你好啊"); } }); s.pack(); s.setVisible(true); }
(2) Case 2
Requirements: Select an option to output the corresponding information on the console
public static void main(String[] args) { Frame s=new Frame("标题"); Box b= Box.createHorizontalBox(); TextField tf=new TextField(30); Choice c=new Choice(); c.add("红色"); c.add("蓝色"); c.add("白色"); b.add(c); b.add(tf); tf.addTextListener(new TextListener() { @Override public void textValueChanged(TextEvent e) { System.out.println("你当前输入的文本="+tf.getText()); } }); c.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { System.out.println("你当前选中的选项="+e.getItem()); } }); s.add(b); s.pack(); s.setVisible(true); }
(3) Case 3
Requirement: Set event monitoring for closing the window, and exit the program after clicking Close
public static void main(String[] args) { Frame s=new Frame("标题"); s.setSize(500,500); s.setLocation(500,500); s.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); // s.pack(); s.setVisible(true); }