導航:首頁 > 編程語言 > java自定義listener

java自定義listener

發布時間:2024-06-08 06:28:52

『壹』 java 自定義事件的觸發及監聽

JAVA事件響應機制

1,先自定義一個事件

public class MyEvent extends java.util.EventObject{
public MyEvent(Object source)
{
super(source);
}
}

2,再自定義一個監聽器

public class MyListener implements java.util.EventListener{
//這里是當事件發生後的響應過程
public void EventActivated(MyEvent me)
{
System.out.println("事件已經被觸發");
}
}

3,以下這個類為觸發事件的事件源

public class MyObject {
private Vector vectorListeners=new Vector();

public synchronized void addMyListener(MyListener ml)
{
vectorListeners.addElement(ml);
}

public synchronized void removeMyListener(MyListener ml)
{
vectorListeners.removeElement(ml);
}

protected void activateMyEvent()
{
Vector tempVector=null;

MyEvent e=new MyEvent(this);

synchronized(this)
{
tempVector=(Vector)vectorListeners.clone();

for(int i=0;i<tempVector.size();i++)
{
MyListener ml=(MyListener)tempVector.elementAt(i);
ml.EventActivated(e);
}
}

}

//定義一個公用方法用於觸發事件
public void test()
{
activateMyEvent();
}
}

4,測試類

public class Test {

public static void main(String[] args)
{
MyObject mo=new MyObject();

//注冊該事件
mo.addMyListener(new MyListener());

//觸發該事件
mo.test();
}
}

『貳』 濡備綍鍦╯truts+spring+hibernate欏圭洰涓瀹炵幇瀵圭嚎紼嬬殑鐩戞帶錛

鍦↗ava Web欏圭洰涓錛岀粡甯歌佸湪欏圭洰寮濮嬭繍琛屾椂鍚鍔ㄤ竴涓綰跨▼錛屾瘡闅斾竴瀹氱殑鏃墮棿灝辮繍琛屼竴瀹氱殑浠g爜錛屾瘮濡傛壂鎻忔暟鎹搴撶殑鍙樺寲絳夌瓑銆傝佸疄鐜拌繖涓鍔熻兘錛屽彲浠ョ幇鍦╳eb.xml鏂囦歡涓瀹氫箟涓涓狶istener錛岀劧鍚庡湪榪欎釜Listener涓鍚鍔ㄤ竴涓綰跨▼錛屽湪綰跨▼閲岄潰瀹炵幇鍔熻兘銆
1. 鑷瀹氫箟Listener
鍦⊿truts+Spring+Hibernate鐨刉eb欏圭洰涓錛寃eb.xml閲岄潰涓鑸閮戒細鏈夎繖鏍風殑浠g爜錛
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

榪欏嚑鍙ヤ唬鐮佷嬌寰梂eb欏圭洰鐨勫瑰櫒錛堜篃灝辨槸Web鏈嶅姟鍣錛屾瘮濡俆omcat錛夊湪欏圭洰鍚鍔ㄦ椂瀹炰緥鍖栦簡涓涓猳rg.springframework.web.context.ContextLoaderListener綾匯
綾諱技鐨勶紝鎴戜滑涔熷彲浠ュ湪web.xml閲岄潰鑷宸卞畾涔変竴涓狶istener錛岃¦eb鏈嶅姟鍣ㄥ幓瀹炰緥鍖栵細
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
<listener-class>com.XXX.listener.WSListener</listener-class>
</listener>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
鍦ㄤ互涓婄殑web.xml鏂囦歡涓錛屾垜浠灝辮¦eb鏈嶅姟鍣ㄥ湪鍚鍔ㄦ椂瀹炰緥鍖栨垜浠鑷宸卞畾涔夌殑com.XXX.listener.WSListener綾伙紙涓鑸鑷宸卞畾涔夌殑Listener綾昏佸啓鍦╫rg.springframework.web.context.ContextLoaderListener鐨勫悗闈錛夛紝鐒跺悗鍦ㄨョ被涓鍘誨惎鍔ㄧ嚎紼嬶細
public class WSListener implements ServletContextListener{
private WSThread wsThread;

@Override public void contextDestroyed(ServletContextEvent event) { // TODO Auto-generated method stub
if (wsThread != null && wsThread.isRunning){
wsThread.stopThread();
}
}

@Override public void contextInitialized(ServletContextEvent event) { // TODO Auto-generated method stub
if (wsThread == null){
wsThread = new WSThread(event);
wsThread.start();
}
}

}
Listener綾繪槸鐢盬eb鏈嶅姟鍣ㄧ$悊鐨勶紝褰揥eb鏈嶅姟鍣ㄥ惎鍔ㄦ椂錛屽皢Listener綾誨疄渚嬪寲騫惰皟鐢ㄥ叾contextInitialized(ServletContextEvent event)鏂規硶錛屽綋Web鏈嶅姟鍣ㄥ叧闂鏃訛紝璋冪敤鍏禼ontextDestroyed(ServletContextEvent event)鏂規硶錛屽洜姝ゆ垜浠鍙浠ュ垎鍒鍦ㄨ繖涓や釜鏂規硶閲岄潰瀹炵幇綰跨▼鐨勫惎鍔ㄥ拰緇撴潫銆
2. 鍦⊿pring瀹瑰櫒浠ュ栬幏寰楀叾鍐呴儴鐨凚ean鐨勫疄渚嬬殑寮曠敤
琚鍚鍔ㄧ殑綰跨▼鐢ㄤ簬闂撮殧涓瀹氱殑鏃墮棿鎵鎻忎竴嬈℃暟鎹搴擄紝鎵懼嚭鏂板炲姞鐨勬暟鎹銆傚湪涓鑸鐨凷truts+Spring+Hibernate鐨刉eb欏圭洰涓錛孲pring瀹瑰櫒涓鐨凚ean鏄鐢盨pring瀹瑰櫒綆$悊鐨勶紝鑰屾垜浠榪欓噷鍚鍔ㄧ殑綰跨▼騫朵笉鍦⊿pring瀹瑰櫒涓錛岄偅涔堟庢牱鑾峰緱Spring瀹瑰櫒涓瑽ean鐨勫疄渚嬬殑寮曠敤榪涜岃塊棶鏁版嵁搴撳憿錛熷彲浠ヤ嬌鐢⊿pring鐨刉ebApplicationContextUtils宸ュ叿綾伙紝璇ュ伐鍏風被鑾峰緱Spring瀹瑰櫒鐨勫紩鐢錛屽啀鑾峰緱鍏跺唴閮ㄧ殑Bean鐨勫疄渚嬬殑寮曠敤銆
綰跨▼鐨勪唬鐮侊細
public class WSThread extends Thread{ public volatile boolean isRunning = true; // 涓ゆ℃壂鎻忎箣闂翠紤鐪犵殑鏃墮棿
public long s_time; private WebApplicationContext context; private PropService propService; private Prop prop; private Temp2Service temp2Service; private Temp2 temp2;
private TempService tempService;

ServletContextEvent event; public WSThread(ServletContextEvent e){ this.event = e; this.context = WebApplicationContextUtils.(event.getServletContext()); this.propService = (PropService) context.getBean("propService"); this.temp2Service = (Temp2Service) context.getBean("temp2Service");
}
public void run(){ while (isRunning){ try { this.prop = propService.findByName("scan_time"); this.s_time = Integer.parseInt(prop.getValue())*1000;
sleep(s_time);
System.out.println("Run!!!!!!");
} catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace();
}
}
}
public void stopThread(){
isRunning = false;
}
public boolean isRunning(){ return isRunning;
}

}
鍦ㄨョ嚎紼嬬殑鏋勯犲嚱鏁頒腑錛屼嬌鐢ㄤ簡浠嶭istener浼犺繃鏉ョ殑ServletContextEvent鍙橀噺錛岀敤璇ュ彉閲忕殑getServletContext()鏂規硶錛岃幏鍙朩eb欏圭洰鐨剆ervletContext錛岀劧鍚庡啀浠ヨ繖涓猄ervletContext浣滀負鍙傛暟錛屼嬌鐢╓ebApplicationContextUtils鐨刧()鏂規硶鑾峰彇ApplicationContext瀵硅薄錛屾渶鍚庡啀閫氳繃ApplicationContext鐨刧etBean()鏂規硶鑾峰彇鍒癇ean鐨勫疄渚嬶紝瀹炵幇瀵規暟鎹搴撶殑璁塊棶銆

『叄』 淺析Java語言的事件處理快捷回復

在JAVA程序設計中 事件的處理是非常重要的 尤其是在需要自定義事件和設計JavaBean時 對事件的處理過程有一個完整的認識對於編程是很有幫助的

下面用一個演示性的例子來說明事件及其處理過程

一 事件的組成

如果想要自定義一個事件 則必須提供一個事件的監聽介面以及一個事件類 在JAVA中監聽介面繼承java util EventListener 事件類繼承java util EventObject 很多基本的事件在編程環境中都已經提供可以很方便使用 但是在自定義事件中必須要要了解這些

下面是一個事件類的代碼 事件類可以向用戶處理程序提供被監聽類的信息

import java util *;

public class PropertyEvent extends EventObject {

public PropertyEvent(){}

}

下面是監聽介面的代碼

import java util *;

public interface PropertyListener extends EventListener {

public void propertyChanged(PropertyEvent propertyEvent);

}

二 事件的處理機制

下面是一段簡要的被監聽類代碼 通過代碼分析事件處理過程

import java util *;

public class Exam {

private int property;

//listeners用來存放已注冊的監聽對象

private Set listeners= new HashSet();

public void addListener(PropertyListener propertyListener){

//listeners必須保證只能被一個線程訪問

synchronized(listeners){

listeners add(propertyListener);

}

}

public void firePropertyChange(){

Iterator iterator;

synchronized(listeners){

//將listeners中的類名放到iterator

iterator = new HashSet(erator();

}

//創建事件類

PropertyEvent propertyEvent = new PropertyEvent();

while(iterator hasNext()){

PropertyListener propertyListener = (propertyListener) iterator next();

//調用用戶的事件處理程序

propertyListener propertyChanged(propertyEvent);

}

}

}

當屬性值發生變化時 首先進行內部處理調用firePropertyChange方法 產生一個事件對象然後用事件對象為參數來調用用戶的事件處理程序

三 事件處理的使用

基本用法

public Exam exam;

exam addListener(this);

public void propertyChange(PropertyEvent event){ }

注 exam是被監聽對象 this為監聽對象 是已經實現了介面方法的當前類 addListener

將當前類注冊到listeners

一個被監聽對象可以有多個監聽對象

exam addListener(listener );

exam addListener(listener );

這樣當exam的property發生變化時 actionListener 和actionListener 的處理程序都會

被調用 當然listener 和listener 必須都是已實現介面方法的類

被監聽的對象也可以是實現了方法的介面

exam addListener(

new PropertyListener(){

//用戶定義事件處理過程

public void propertyChange(PropertyEvent event){

}

);

lishixin/Article/program/Java/hx/201311/26740

『肆』 JAVA添加按鈕監聽器

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class ShowButton implements ActionListener{
private JTextField textField = null;
private JButton button = null;
private JFrame frame = null;

public ShowButton(){
frame = new JFrame("顯示按鈕文字");
button = new JButton("3");
textField = new JTextField("",20);
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
frame.add(textField);
button.addActionListener(this);
frame.add(button);
frame.setSize(400, 100);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {
textField.setText("");
textField.setText(button.getActionCommand());
System.out.println(button.getActionCommand()+"===");
}

public static void main(String[] args) {
new ShowButton();
}

}

『伍』 關於java的監聽器

1、public void addWindowListener(WindowListener l)添加指定的窗口偵聽器,以從此窗口接收窗口事件。如果 l 為 null,則不拋出任何異常,且不執行任何操作。

這個是API中的方法定義,此方法參數為介面WindowListener,任何實現該介面的類都可以作為參數。

2、public abstract class WindowAdapterimplements WindowListener, WindowStateListener, WindowFocusListener

接收窗口事件的抽象適配器類。此類中的方法為空。此類存在的目的是方便創建偵聽器對象。

擴展此類可創建 WindowEvent 偵聽器並為所需事件重寫該方法。(如果要實現
WindowListener 介面,則必須定義該介面內的所有方法。此抽象類將所有方法都定義為
null,所以只需針對關心的事件定義方法。)

使用擴展的類可以創建偵聽器對象,然後使用窗口的 addWindowListener
方法向該窗口注冊偵聽器。當通過打開、關閉、激活或停用、圖標化或取消圖標化而改變了窗口狀態時,將調用該偵聽器對象中的相關方法,並將
WindowEvent 傳遞給該方法。

3、如果我想在代碼中一次性使用某個類(抽象類或具體類)或介面,可以使用匿名類的方式,這樣不需自己定義一個My***類,然後再使用,比較方便。用法就是直接在new WindowAdapter()後面加入類定義,在其中實現或覆蓋方法就可以了。

匿名類不是返回值,而是相當於new String(「hello」)這種的擴展形式。我覺得匿名類的最多用處就是加監聽器時。

附上WindowAdapter源代碼:


implementsWindowListener,WindowStateListener,WindowFocusListener
{
publicvoidwindowOpened(WindowEvente){}

publicvoidwindowClosing(WindowEvente){}

publicvoidwindowClosed(WindowEvente){}

publicvoidwindowIconified(WindowEvente){}

publicvoidwindowDeiconified(WindowEvente){}

publicvoidwindowActivated(WindowEvente){}

publicvoidwindowDeactivated(WindowEvente){}

publicvoidwindowStateChanged(WindowEvente){}

publicvoidwindowGainedFocus(WindowEvente){}

publicvoidwindowLostFocus(WindowEvente){}
}

『陸』 java怎樣監聽一個值是否發生了變化,具體代碼

java 自定義監聽器監聽屬性變化
import java.util.EventObject;

public class MyEvent extends EventObject
{
private Object obj;
private String sName;

public MyEvent(Object source,String sName)
{
super(source);
this.obj=source;
this.sName=sName;
}

public Object getObj()
{
return obj;
}

public String getsName()
{
return sName;
}
}

import java.util.EventListener;

public interface MyEventListener extends EventListener
{

public void handleEvent (MyEvent me);

}

import java.util.Iterator;
import java.util.Vector;

import demo.DemoEvent;

public class MyEventSource
{
private Vector list=new Vector();
private String sName = "";

public MyEventSource()
{
super();
}
public void addMyEventListener(MyEventListener me)
{
list.add(me);
}
public void deleteMyEventListener(MyEventListener me)
{
list.remove(me);
}
public void notifyMyEvent(MyEvent me)
{
Iterator it=list.iterator();
while(it.hasNext())
{
((MyEventListener) it.next()).handleEvent(me);
}
}
public void setName(String str)
{
boolean bool = false;
if (str == null && sName != null)
bool = true;
else if (str != null && sName == null)
bool = true;
else if (!sName.equals(str))
bool = true;
this.sName = str;
// 如果改變則執行事件
if (bool)
notifyMyEvent(new MyEvent(this, sName));
}
public String getsName()
{
return sName;
}

}

public class Test implements MyEventListener
{
public Test()
{
MyEventSource mes = new MyEventSource();
mes.addMyEventListener(this);
mes.setName("niu");
}

public static void main(String args[])
{
new Test();
}

public void handleEvent(MyEvent me)
{
System.out.println(me.getSource());
System.out.println(me.getsName());
}
}

『柒』 java自定義事件,線程a如何每一秒鍾觸發一個事件,然後另一個線程b監聽之,並作出反應

思路,在線程b的操作中調用a.wait(),線程a中觸發的事件後面添加notify(),則在b執行到a.wait()的時候,回b等待a,a執行到notify(),通知a的等答待列表中的b線程進入鎖池,此時b有機會繼續執行,這樣就打到了線程b監聽a執行完事件

『捌』 java中怎樣用KeyListener寫一個組合的鍵盤監聽事件

最關鍵的一句:
if(e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown())

我寫了一個測試程序你可以看看,快捷是Ctrl+Enter,列印出OK

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Test extends JFrame implements KeyListener {
Test() {
this.addKeyListener(this);
this.setBounds(0,0,100,100);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void keyPressed(KeyEvent e) {
// TODO 自動生成方法存根
if(e.getKeyCode() == KeyEvent.VK_K && e.isControlDown()){
System.out.println("OK");
}
}

public static void main(String[] args) {
new Test();
}

public void keyReleased(KeyEvent e) {
// TODO 自動生成方法存根

}

public void keyTyped(KeyEvent e) {
// TODO 自動生成方法存根

}
}

閱讀全文

與java自定義listener相關的資料

熱點內容
手機QQ怎麼不能傳文件 瀏覽:450
u盤復制文件的速度取決於什麼 瀏覽:659
iphone4下拉通知欄 瀏覽:427
javasocket接收數據包 瀏覽:137
如何給類數據成員變數設置默認值 瀏覽:885
密集app怎麼推廣 瀏覽:866
WP7屏幕保護程序 瀏覽:568
win10雙硬碟老藍屏 瀏覽:986
怎麼設置網站描述 瀏覽:274
微信壓縮包可以發送多大文件 瀏覽:916
u盤打開很卡無法復制裡面文件 瀏覽:143
app怎麼刪不掉 瀏覽:324
農村工作一號文件圖片 瀏覽:598
錘子手機怎麼樣升級 瀏覽:706
微信朋友圈哲理說說 瀏覽:649
jscss模板 瀏覽:472
圖片文件夾里多了一個 瀏覽:305
索尼a7r2配置文件 瀏覽:706
獲取jsp中a中text 瀏覽:396
電腦word文件怎麼找回來 瀏覽:846

友情鏈接