swing的事件处理机制?
Swing的事件处理机制是一种基于事件监听器的模型,它允许组件在某些事件发生时执行某些操作。当一个事件发生时,Swing会创建一个事件对象,然后将它传递给事件监听器。
监听器可以是预定义的,也可以是用户自定义的,它们会根据事件类型执行相应的操作。Swing支持多种类型的事件,包括鼠标事件、键盘事件、焦点事件等。通常,事件监听器会注册到组件上,当事件发生时,组件会通知监听器执行相应的操作。
这种事件驱动的机制使得Swing应用程序可以响应用户的交互行为,并且具有良好的扩展性和灵活性。
就是事件的“处理方”向事件的“发出方”先行注册,当事件发生时,事件的“发生方”负责通知事件的“处理方”。
譬如编写一个窗口,用到了JFrame,我想实现一个功能,当按下Q键时,窗口关闭。
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 5671798241966272024L;
public static void main(String[] args) {
new TestFrame();
}
pack函数作用?
pack() - 类 java.awt.Window 中的方法 调整此窗口的大小,以适合其子组件的首选大小和布局。 pack(JarFile, OutputStream) - 接口 java.util.jar.Pack200.Packer 中的方法 接收 JarFile 并将其转换为 Pack200 存档。
pack(JarInputStream, OutputStream) - 接口 java.util.jar.Pack200.Packer 中的方法 接收 JarInputStream 并将其转换成 Pack200 存档。 pack() - 类 javax.swing.JInternalFrame 中的方法 使此 JInternalFrame 的子组件按其首选大小进行布局。
pack() - 类 javax.swing.JPopupMenu 中的方法 布置容器,让它使用显示其内容所需的最小空间。
为什么一提到java的swing和awt组件,大家都不建议学?
早期的java主要是应用在web开发方面,所以从实用的角度出发,确实可以略过AWT和Swing的学习。在移动端开发流行之后,AWT和Swing又成为一个必修的内容了,因为做Android开发如果有一定的AWT基础是比较好的,很多概念是统一的。
为了描述这个问题,我们首先要了解到底什么是AWT,什么是Swing,以及它们与Android开发有什么联系。
AWT与Swing
java语言第一个支持图形界面开发的API就是AWT,在AWT中定义了java图形界面的很多核心概念,所以要了解java的图形界面开发方式一定要从了解AWT开始。下面分别介绍一下AWT中的三个核心概念:容器、组件、布局。
图形容器是存放图形元素的场所和环境,java中把容器分为顶级容器和次顶级容器。顶级容器可以单独显示、次顶级容器不能单独显示。顶级容器的代表是Frame,次顶级容器的代表是Panel。
图形组件是具体的图形应用元素,比如Button(按钮)、TextField(文本框)、Label(标签)、Choice(下拉列表)等等,每一个图形组件代表一种具体的图形应用元素。
布局的作用是安排图形组件在容器中的排列样式,常见的布局方式有BorderLayout、FlowLayout和GridLayout等。其中BorderLayout是Frame的默认布局管理器,FlowLayout是Panel的默认布局管理器。
具体的图形开发根据不同的界面设计采用不同的容器、布局和组件进行搭配组合,复杂的图形组件遵循顶级容器嵌套次顶级容器的方式来完成。
Swing与AWT相比较最大的优点是轻量级方式,Swing不依赖于本地操作系统,所以在样式上能够进行统一。在写法上采用了在AWT的类名基础上增加一个大写的J字符,比如在AWT中的Frame改为JFrame,Button改为JButton等等。
在实际的开发中比较推荐使用Swing的方式,一个原因是Swing的组件在外观上更具备科技感,另一个原因是它占用的资源较AWT更少。
事件处理
说到AWT和Swing一定要说一下图形组件的事件处理方式,Java中的事件处理方式采用了监听的方式,也可以称为“代理”的方式。事件处理类通过实现具体的接口来完成对应的事件处理,比如ActionEvent对应的ActionListener接口;KeyEvent对应的KeyListener接口;MouseEvent对应的MouseListener接口和MouseMotionListener接口;WindowEvent对应的WindowListener接口等等。
这种处理方式让图形界面类和事件处理类进行了有效的分离,在代码处理上更加方便和灵活,在Swing的很多组件中也遵循了MVC的结构,让代码更加容易模块化。
总的来说java中的事件处理并不复杂,通过一定的实验就能完全掌握,所有这并不是学习的负担。
AWT与Android开发的关系
传统的java图形处理方式并不完全适用于Android开发,在Android开发中通常采用配置文件的方式来完成Activity的创建,当然也可以使用代码的方式来完成Android的界面开发。
不管使用哪种方式来创建Android界面,大体的概念是一致的,比如布局、组件等等,只不过名称上有所区别,比如AWT中的Flowlayout对应于Android的布局是LinearLayout等,虽然名称不同但是概念是一致的。
事件处理方式也是大体一致,不过android开发中提供了基于回调的事件处理方式,这种方式在做一些简单的事件处理时比较方便。
所以如果将来要从事Android开发还是建议系统地学习一下AWT或Swing。
关注我,学习更多关于java开发的内容。
还没有评论,来说两句吧...