当前位置:网站首页>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全套视频教程:
边栏推荐
- 七夕节代码表白
- The test salary is so high?20K just graduated
- 2022.8.4-----leetcode.1403
- Never put off till tomorrow what you can put - house lease management system based on the SSM
- UE4 opens doors with overlapping events
- [Paper Notes] MapReduce: Simplified Data Processing on Large Clusters
- IJCAI2022 | DictBert: Pre-trained Language Models with Contrastive Learning for Dictionary Description Knowledge Augmentation
- Acid (ACID) Base (BASE) Principles for Database Design
- Ice Scorpion V4.0 attack, security dog products can be fully detected
- YYGH-13-Customer Service Center
猜你喜欢
Based on holding YOLOv5 custom implementation of FacePose YOLO structure interpretation, YOLO data format conversion, YOLO process modification"
presto启动成功后出现2022-08-04T17:50:58.296+0800 ERROR Announcer-3 io.airlift.discovery.client.Announcer
shell脚本:for循环与while循环
36-Jenkins-Job Migration
Bubble Sort and Quick Sort
.NET Application -- Helloworld (C#)
[Software testing] unittest framework for automated testing
public static <T> List<T> asList(T... a) 原型是怎么回事?
2022 High-level installation, maintenance, and removal of exam questions mock exam question bank and online mock exam
静态方法获取配置文件数据
随机推荐
ffmpeg 枚举decoders, encoders 分析
Beyond YOLO5-Face | YOLO-FaceV2 officially open source Trick+ academic point full
毕设-基于SSM房屋租赁管理系统
ffmpeg pixel format basics
Increasing leetcode - a daily topic 1403. The order of the boy sequence (greed)
UE4 后期处理体积 (角色受到伤害场景颜色变淡案例)
AI+PROTAC | dx/tx completes $5 million seed round
The second council meeting of the Dragon Lizard Community was successfully held!Director general election, 4 special consultants joined
Details such as compiling pretreatment
How to Add Category-Specific Widgets in WordPress
The most effective seven performance testing techniques of software testing techniques
从“能用”到“好用” 国产软件自主可控持续推进
YYGH-13-Customer Service Center
YYGH-13-客服中心
Leading the highland of digital medicine, Zhongshan Hospital explores to create a "new paradigm" for future hospitals
IJCAI2022 | DictBert: Pre-trained Language Models with Contrastive Learning for Dictionary Description Knowledge Augmentation
2022.8.4-----leetcode.1403
[TA-Frost Wolf_may-"Hundred Talents Project"] Graphics 4.3 Real-time Shadow Introduction
10 years of testing experience, worthless in the face of the biological age of 35
The sword refers to Offer--find the repeated numbers in the array (three solutions)