JAVA SWT事件四種寫法實(shí)例解析
一:匿名內(nèi)部類寫法
在一個組件下加入以下語句
text.addMouseListener(new MouseAdapter(){ public void mouseDoubleClich(MouseEVent e){ MessageDialog.openInformation(null,'','helloworld'):}})
這種方式是在事件內(nèi)部直接實(shí)現(xiàn)處理代碼,優(yōu)點(diǎn)是簡單方便,但也存在缺點(diǎn)
①:事件處理代碼會分散的出現(xiàn)在各個部分,維護(hù)起來不方便;
②:如果代碼較長,閱讀和維護(hù)起來麻煩
③:當(dāng)工具欄、菜單欄也需要相同的行為時,代碼無法重用,導(dǎo)致代碼臃腫
二:命名內(nèi)部類寫法:
text.addMouseListener(new MyMouseDoubleClick());...//定義MyMouseDoubleClick.javaprivate static final class MyMouseDoubleClick extends MouseAdapter{ public void mouseDoubleClick(MouseEvent e){ MessageDialog.openInformation(null,'','hello world')}}
三:外部類寫法:
這種方法與第二種方法類似,只是有內(nèi)部類變?yōu)閱蝹€外部類
四:實(shí)現(xiàn)監(jiān)聽器接口的寫法:
將類實(shí)現(xiàn)相應(yīng)的接口,這樣類本身就成了一個監(jiān)聽器,使得加入監(jiān)聽器的代碼可以更簡潔,這種方法適合加入監(jiān)聽器的組件較多,且要求監(jiān)聽器的事件處理代碼可以被組件共用,需要注意的是
事件方法和其他方法混合在一起,所以應(yīng)加一些注釋來說明。沒用事件處理方法可以用空來實(shí)現(xiàn)。如果繼承了了相應(yīng)的事件適配器,則可根據(jù)需要寫相應(yīng)的方法,另外需要注意,只有接口才有多繼承的特性,所以如果類本身已經(jīng)是一個子類,則只有通過實(shí)現(xiàn)接口的方式來實(shí)現(xiàn)而不能繼承接口的適配器。
public class Helloworld extends MouseAdapter implements MouseListener{ public static void main(String[] args){ ....... Text text1=new Text(shell,SWT.Border); Text text2=new Text(shell, SWt.Border); text1.addMouseListener(this); text2.addMouseListener(this);} public void mouseDoubleClick(MouseEvent e){ MessageDialog.openInformation(null,'','hello world');}}}}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移2. 怎樣才能用js生成xmldom對象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?3. 使用HttpClient增刪改查ASP.NET Web API服務(wù)4. intellij idea寫Python教程5. Python 用NumPy創(chuàng)建二維數(shù)組的案例6. jsp filter 過濾器功能與簡單用法示例7. ASP中if語句、select 、while循環(huán)的使用方法8. 使用HttpClient消費(fèi)ASP.NET Web API服務(wù)案例9. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲10. asp中response.write("中文")或者js中文亂碼問題
