標籤: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開發小結:用得比較順手的事件監聽