Java開發小結:用得比較順手的事件監聽

來源:互聯網
上載者:User

標籤:cte   listen   sso   通過   over   響應   turn   分享   set   

        第一次聽說監聽是三年前,做一個webGIS的項目,當時對Listener的印象就是個“監視器”,監視著介面的一舉一動,一有動靜就觸發對應的響應。

         通過對介面的某一或某些操作添加監聽,可以自發地調用監聽函數/監聽類,對操作作出反應。舉個栗子:被監聽的操作是“你惹你媽生氣了”,添加的響應是“你媽給你爸打電話,你爸回家了,你爸打你一頓 ”。所以不管什麼時候,只要“你惹你媽生氣了”,都會觸發這個操作的監聽,最終結果是每次你都會被你爸打一頓。屢試不爽,無一例外。這就是事件監聽,java.util.EventListener。

        Listener分很多種,但我總結不出來一個宏觀架構,這裡只把常用的CS監聽列出來講講,不足留待以後補充:ActionListener,MouseListener,PopMenuListener等等。

           

1. 直接在控制項中添加監聽,如給“儲存按鈕”添加ActionListener監聽

 

1         saveCharaEditButton.addActionListener(new ActionListener() {2             3             @Override4             public void actionPerformed(ActionEvent e) {5                 // TODO Auto-generated method stub6                 save();7             }8         });

 

2.寫一個監聽類,繼承監聽介面。添加事件監聽時只需要 實現這個監聽類就ok了

 1     public JPanel setRightPanel(){ 2         JPanel rightPanel = new JPanel(); 3         double[][] size = {{15,TableLayout.FILL,30,TableLayout.FILL,35},{10,30,10,TableLayout.FILL}}; 4         rightPanel.setLayout(new TableLayout(size)); 5         JButton saveCharaEditButton = new JButton("儲存編輯"); 6         JButton enableCharaEditButton = new JButton("啟用編輯"); 7         rightPanel.add(enableCharaEditButton, "1,1"); 8         rightPanel.add(saveCharaEditButton, "3,1"); 9         rightPanel.add(setCharaJCTablePanel(), "0,3,4,3");10         saveCharaEditButton.addActionListener(new saveEditToFloodCharacterValueListener());//添加監聽11         return rightPanel;12     }
 1     class saveEditToFloodCharacterValueListener implements ActionListener{ 2  3         @Override 4         public void actionPerformed(ActionEvent e) { 5             // TODO Auto-generated method stub 6             FloodCharacterValue floodCharacterValue = new FloodCharacterValue();             7             floodCharacterValue = FloodCharacterValue.transFldPropToFloodCharacterValue(editCharaFldprop); 8             m_doc.m_floodExtractCharacterValue = floodCharacterValue; 9         }10     }

 

Java開發小結:用得比較順手的事件監聽

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.