当前位置:网站首页>There are several common event handling methods in Swing?How to listen for events?
There are several common event handling methods in Swing?How to listen for events?
2022-08-05 03:34:00 【is a samoyed】
在Swing中,提供了丰富的事件,这些事件大致可以分为窗体事件(WindowEvent)、鼠标事件(MouseEvent)、键盘事件(KeyEvent)、动作事件(ActionEvent)等.接下来,These common events will be explained in detail in this section.
1.窗体事件
大部分GUI应用程序都需要使用Window窗体对象作为最外层的容器,Lets say the form object is allGUI应用程序的基础,Applications usually add other components directly or indirectly to the form.
当对窗体进行操作时,例如窗体的打开、关闭、激活、停用等,这些动作都属于窗体事件,Java中提供了一个WindowEvent类用于表示窗体事件.在应用程序中,当对窗体事件进行处理时,首先需要定义一个实现了WindowListener接口的类作为窗体监听器,然后通过addWindowListener()方法将窗体对象与窗体监听器进行绑定.
Next, a case is used to implement the monitoring of form events,如文件1所示.
文件1 Example07.java
import java.awt.event.*;
import javax.swing.*;
public class Example07 {
private static void createAndShowGUI() {
JFrame f = new JFrame("WindowEvent");
f.setSize(400, 300);
f.setLocation(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 使用内部类创建WindowListener实例对象,监听窗体事件
f.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened---窗体打开事件");
}
public void windowIconified(WindowEvent e) {
System.out.println("windowIconified---窗体图标化事件");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("windowDeiconified---窗体取消图标化事件");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("windowDeactivated---窗体停用事件");
}
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing---窗体正在关闭事件");
}
public void windowClosed(WindowEvent e) {
System.out.println("windowClosed---窗体关闭事件");
}
public void windowActivated(WindowEvent e) {
System.out.println("windowActivated---窗体激活事件");
}
});
}
public static void main(String[] args) {
// 使用SwingUtilities工具类调用createAndShowGUI()方法并显示GUI程序
SwingUtilities.invokeLater(Example07::createAndShowGUI);
}
}
运行结果如图所示.
文件1中,通过WindowListenerListen to the form event of the operation window,When a specific action is received,print the name of the triggered event.Then the picture8-11Form event source shown for event manipulation,perform minimization separately、Click the taskbar icon、When the close button is clicked,The window event listener will monitor and respond to the corresponding operation,结果如下图所示.
2.鼠标事件
在图形用户界面中,Users will often use the mouse to make selections、切换界面等操作,这些操作被定义为鼠标事件,which includes mouse down、鼠标松开、鼠标单击等.Java中提供了一个MouseEvent类用于表示鼠标事件,几乎所有的组件都可以产生鼠标事件.处理鼠标事件时,首先需要通过实现MouseListener接口定义监听器(也可以通过继承适配器MouseAdapter类来实现),然后调用addMouseListener()方法将监听器绑定到事件源对象.
Next, learn how to monitor mouse events through a case,如文件2所示.
文件2 Example08.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example08 {
private static void createAndShowGUI() {
JFrame f = new JFrame("MouseEvent");
f.setLayout(new FlowLayout()); // Set the layout for the window
f.setSize(300, 200);
f.setLocation(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton but = new JButton("Button");// 创建按钮对象
f.add(but); // Add a button component to the window
// Add mouse event listener for button
but.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased-鼠标放开事件");
}
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed-鼠标按下事件");
}
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited—鼠标移出按钮区域事件");
}
public void mouseEntered(MouseEvent e) {
System.out.println("mouseEntered—鼠标进入按钮区域事件");
}
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked-鼠标完成单击事件");
}
});
}
public static void main(String[] args) {
// 使用SwingUtilities工具类调用createAndShowGUI()方法并显示GUI程序
SwingUtilities.invokeLater(Example08::createAndShowGUI);
}
}
运行结果如图所示.
在上图中,Use the mouse to operate the buttons on the window,Move the mouse into the button area first,Then click the button and release,Move out of the button area,The output information of the console is shown in the following figure.
从图可以看出,When the mouse makes the corresponding action on the button,The listener gets the corresponding event object,So print out the event name corresponding to the action.
读者可能会问,The operation of the mouse is divided into left-click single double-click and right-click single double-click,And there's a scroll wheel action.Only the handling of these events is given above,Can it meet actual needs??答案是肯定的,MouseEventThere are many constants defined in the class to identify mouse actions.如下面的代码所示:
public void mouseClicked(MouseEvent e) {
if(e.getButton()==MouseEvent.BUTTON1){
System.out.println("鼠标左击事件");
}
if(e.getButton()==MouseEvent.BUTTON3){
System.out.println("鼠标右击事件");
}
if(e.getButton()==MouseEvent.BUTTON2){
System.out.println("鼠标中键单击事件");
}
}
从上面的代码可以看出,MouseEvent类中针对鼠标的按键都定义了对应的常量,可以通过MouseEvent对象的getButton()Method to get the key value of the operated button,从而判断是哪个按键的操作.另外,The number of mouse clicks can also beMouseEvent对象的getClickCount()方法获取到.因此,在鼠标事件中,can be operated according to different,做出相应的处理.
3.键盘事件
Keyboard operation is also the most common user interaction method,e.g. keyboard press、释放等,这些操作被定义为键盘事件.Java中提供了一个KeyEvent类表示键盘事件,处理KeyEvent事件的监听器对象需要实现KeyListener接口或者继承KeyAdapter类,然后调用addKeyListener()方法将监听器绑定到事件源对象.
Next, learn how to listen for keyboard events through a case,如文件3所示.
文件3 Example09.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example09 {
private static void createAndShowGUI() {
JFrame f = new JFrame("KeyEvent");
f.setLayout(new FlowLayout());
f.setSize(400, 300);
f.setLocation(300, 200);
JTextField tf = new JTextField(30); // 创建文本框对象
f.add(tf); // 在窗口中添加文本框组件
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 为文本框添加键盘事件监听器
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// 获取对应的键盘字符
char keyChar = e.getKeyChar();
// 获取对应的键盘字符代码
int keyCode = e.getKeyCode();
System.out.print("键盘按下的字符内容为:" + keyChar+" ");
System.out.println("键盘按下的字符代码为:" + keyCode);
}
});
}
public static void main(String[] args) {
// 使用SwingUtilities工具类调用createAndShowGUI()方法并显示GUI程序
SwingUtilities.invokeLater(Example09::createAndShowGUI);
}
}
运行结果如下:
文件3中,用到JTextComponent类的子类JTextField,It only allows editing a single line of text.When typing characters in the file box in the figure,triggers the keyboard event,会执行重写的keyPressed()方法.这时,可以通过KeyEvent类的getKeyChar()method to get the characters typed by the keyboard,通过getKeyCode()The method can get the integer value corresponding to the input character.在上图所示的窗口中,Enter in sequence on the keyboarda、s、1字符时,The console will press the name and key value corresponding to the key(keyCode)打印了出来,如下图所示.
4.动作事件
Action events are different from the previous three events,it does not represent some kind of event,just means that an action happened.例如,when closing a file,可以通过键盘关闭,也可以通过鼠标关闭.Here the reader does not need to care which method is used to close the file,As long as the close button is operated,that triggers the action event.
在Java中,动作事件用ActionEvent类表示,处理ActionEvent事件的监听器对象需要实现ActionListener接口.监听器对象在监听动作时,Does not handle the details of mouse movements and clicks like mouse events,but to deal with something like“按钮按下”这样“有意义”的事件.
Java基础入门:
java零基础自学首Java入门教程(含Java项目和Java真题)
Javaweb核心基础
JavaWeb基础教程,Java web从入门到企业实战完整版
Spring Cloud最全微服务架构:
Spring全套教程,入门到精通
SSM框架教程:
SSM框架教程_Spring+SpringMVC+Maven高级+Spring
SpringBoot2全套视频教程:
边栏推荐
- 高项 02 信息系统项目管理基础
- Queue Topic: Recent Requests
- MRTK3开发Hololens应用-手势拖拽、旋转 、缩放物体实现
- 冰蝎V4.0攻击来袭,安全狗产品可全面检测
- [Filter tracking] based on matlab unscented Kalman filter inertial navigation + DVL combined navigation [including Matlab source code 2019]
- UE4 通过互动(键盘按键)开门
- public static <T> List<T> asList(T... a) 原型是怎么回事?
- 关于#SQL#的迭代、父子结构查询问题,如何解决?
- rpc-remote procedure call demo
- 2022 High-level installation, maintenance, and removal of exam questions mock exam question bank and online mock exam
猜你喜欢

冒泡排序与快速排序

leetcode-每日一题1403. 非递增顺序的最小子序列(贪心)

Web3.0 Dapps——通往未来金融世界的道路

MRTK3开发Hololens应用-手势拖拽、旋转 、缩放物体实现

After the large pixel panorama is completed, what are the promotion methods?

UE4 第一人称角色模板 添加生命值和调试伤害

Never put off till tomorrow what you can put - house lease management system based on the SSM

UE4 在游戏运行时更改变量 (通过鼠标滑轮来更改第一人称角色的最大行走速度)

Walter talked little knowledge | "remote passthrough" that something

用CH341A烧录外挂Flash (W25Q16JV)
随机推荐
Redis key basic commands
Why did they choose to fall in love with AI?
Static method to get configuration file data
Android Practical Development - Kotlin Tutorial (Introduction - Login Function Implementation 3.3)
905. 区间选点
[Paper Notes] MapReduce: Simplified Data Processing on Large Clusters
YYGH-13-Customer Service Center
Detailed and comprehensive postman interface testing practical tutorial
【七夕节】浪漫七夕,代码传情。将爱意变成绚烂的立体场景,给她(他)一个惊喜!(送代码)
Turn: Charles Handy: Who you are is more important than what you do
Redis key基本命令
七夕节代码表白
运维监控系统之Open-Falcon
The sword refers to Offer--find the repeated numbers in the array (three solutions)
Dynamic management of massive service instances
[Filter tracking] based on matlab unscented Kalman filter inertial navigation + DVL combined navigation [including Matlab source code 2019]
新人如何入门和学习软件测试?
Summary of common methods of arrays
IJCAI2022 | DictBert: Pre-trained Language Models with Contrastive Learning for Dictionary Description Knowledge Augmentation
How to find all fields with empty data in sql