天天看點

BeanShell腳本接口之this引用接口類型

比如,我們可以為我們的按鈕寫一個事件處理的腳本,甚至簡單的隻是使用一個全局方法,像這樣:

actionPerformed( event ) { 

  print( event ); 

button = new JButton("Foo!"); 

button.addActionListener( this ); 

frame( button ); 

運作效果

<a href="http://blog.51cto.com/attachment/201201/133441700.png" target="_blank"></a>

點選按鈕後

<a href="http://blog.51cto.com/attachment/201201/133536438.png" target="_blank"></a>

在這裡,我們替換了編寫腳本對象來持有 actionPerformed() 方法,簡單地将方法放置在目前的上下文中(全局範圍)并告訴 BeanShell 到那裡尋找方法。

正如之前,當 ActionEvents 被按鈕觸發,你的 actionPerformed() 方法就會被調用。BeanShell 中我們腳本的“this”引用實作接口并對合适的命名方法發出方法調用的指令,如果該命名方法存在的話。

注意:

如果你有興趣,可以嘗試在一個 Shell 或者指令行中互動式地進入之前的例子。你會發現你可以随時通過簡單地再一次進入

方法的方式重新定義actionPerformed()。每一個按鈕按下以後将會在你的 shell 中找到目前的版本。從某種意義上來講,

你在一個動态的 Java 對象内部工作,在你打字的時候你建立它并且修改它。巧妙嗎?那就是 Bean !

messageButton( message ) { 

  JButton button = new JButton("Press Me"); 

  button.addActionListener( this ); 

  JFrame frame = frame( button ); 

  actionPerformed( e ) { 

    print( message ); 

    frame.setVisible(false); 

  } 

messageButton("Hey you!"); 

messageButton("Another message..."); 

<b>運作效果</b>

<a href="http://blog.51cto.com/attachment/201201/133705505.png" target="_blank"></a>

<b>單擊第一個按鈕後</b>

<a target="_blank"></a>

<b>點選另一個按鈕後</b>

<a href="http://blog.51cto.com/attachment/201201/133834788.png" target="_blank"></a>

上面的例子中建立了兩個帶有各自消息的按鈕。每一個按鈕在推動時列印他們的消息然後将自己解除。這些按鈕通過單獨調用 messageButton() 方法被建立,是以各自有他們自己的方法上下文,單獨的本地變量以及單獨的 ActionListener 接口處理執行個體。各自(其自己的方法上下文)為其按鈕注冊 ActionListener,使用各自的“this”引用。

本文轉自 tongqiuyan  51CTO部落格,原文連結:http://blog.51cto.com/tongqiuyan/761072

繼續閱讀