【Java】【学习】【监听器】Listener的学习的案例(窗体程序)
# JavaWeb 监听器listener 学习与简单应用
Java窗体程序使用监听器
效果:点击按钮,控制台出现文字
代码如下
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
public class edu_Listener {
public static void main(String[] args) {
//创建窗口
JFrame frame = new JFrame();
//设置窗口大小
frame.setSize(250,200);
//设置窗口位置
frame.setLocation(350,250);
//创建按钮
JButton btn = new JButton("Click");
//创建监听器
ActionListener listener = new ActionListener() {
//处理事件的方法(事件处理器)
@Override
public void actionPerformed(ActionEvent e) {
String dateStr = new Date(e.getWhen()).toString();
System.out.println(dateStr);
System.out.println("Hello world !");
}
};//注意这里的分号
// 将监听器注册到按钮(此后监听器会一直处于监听按钮的状态)
btn.addActionListener(listener);
//将按钮添加到窗口
frame.add(btn);
//设置窗口显示状态
frame.setVisible(true);
System.out.println("执行完毕!");
}
}
Javaweb 使用监听器
? | 课件只写了一半
监听器类
类名:MyServletContextListener
代码:
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
@WebListener
public class MyServletContextListener
implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
public MyServletContextListener() {
}
// 在创建ServletContext对象时调用
@Override
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is initialized(when the Web application is deployed). */
}
// 在销毁ServletContext对象时地调用
@Override
public void contextDestroyed(ServletContextEvent sce) {
/* This method is called when the servlet Context is undeployed or Application Server shuts down. */
}
@Override
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
/* Session is destroyed. */
}
@Override
public void attributeAdded(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute is added to a session. */
}
@Override
public void attributeRemoved(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute is removed from a session. */
}
@Override
public void attributeReplaced(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute is replaced in a session. */
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置ServletContextListener生命周期监听器-->
<listener>
<listener-class>MyServletContextListener</listener-class>
</listener>
</web-app>
[未完待续...]
版 权 声 明
作者:萌狼蓝天
QQ:3447902411(仅限技术交流,添加请说明方向)
转载请注明原文链接:https://www.cnblogs.com/zwj/p/java_edu_listenerDemo1.html