首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Swing 事件處理完整手冊:13 大監聽器介面與事件物件詳解

     編輯:Java 程式設計入門

Swing 事件模型基於「事件源—監聽器—事件物件」三元架構。本文系統整理 13 種核心監聽器介面、對應事件類別、關鍵方法與觸發情境,為桌面應用開發提供速查參考。

事件監聽器速查總表

監聽器介面核心方法事件類別關鍵事件方法觸發情境
ActionListener actionPerformed ActionEvent getActionCommand() 取得命令字串
getModifiers() 修飾鍵
getWhen() 時間戳
按鈕點擊、清單選擇、文字欄位 Enter、計時器到期
AdjustmentListener adjustmentValueChanged AdjustmentEvent getAdjustable() 可調整介面
getAdjustmentType() 5 種捲動型別
getValue() 當前值
捲動條操作
ItemListener itemStateChanged ItemEvent getItem() 選中元素(需轉型)
getItemSelectable() 事件源
getStateChange() SELECTED/DESELECTED
核取方塊、選項按鈕、清單選擇
FocusListener focusGained
focusLost
FocusEvent getOppositeComponent() 另一參與元件
isTemporary() 暫時/永久轉移
元件焦點獲得/失去
KeyListener keyPressed
keyReleased
keyTyped
KeyEvent getKeyChar() 字符(僅 keyTyped)
getKeyCode() 鍵盤碼
getKeyModifiersText() 修飾鍵文字
getKeyText() 按鍵名稱
鍵盤輸入
MouseListener mouseClicked
mousePressed
mouseReleased
mouseEntered
mouseExited
MouseEvent getPoint()/getX()/getY() 相對元件座標
getLocationOnScreen() 螢幕絕對座標 (1.6+)
getClickCount() 點擊次數
getButton() 滑鼠鍵
isPopupTrigger() 彈出選單觸發檢查
滑鼠點擊、進入/離開元件
MouseMotionListener mouseDragged
mouseMoved
MouseEvent 同 MouseEvent 座標方法 滑鼠移動/拖曳
MouseWheelListener mouseWheelMoved MouseWheelEvent getScrollType() WHEEL_UNIT/BLOCK_SCROLL
getScrollAmount() 單位捲動量
getWheelRotation() 正負值表方向
滑鼠滾輪捲動
WindowListener 7 方法:
windowOpened
windowClosing
windowClosed
windowIconified
windowDeiconified
windowActivated
windowDeactivated
WindowEvent getWindow() 事件視窗
getOppositeWindow() 另一視窗
getOldState()/getNewState() 狀態變化
視窗開啟/關閉/最小化/啟用/停用
WindowFocusListener windowGainedFocus
windowLostFocus
WindowEvent 同 WindowEvent 視窗焦點獲得/失去
WindowStateListener windowStateChanged WindowEvent getOldState()/getNewState() 視窗狀態變化(最大化/最小化/常態)

實務開發關鍵提示

  • 適配器模式: 針對方法較多的介面(MouseListener、WindowListener 等),繼承對應 Adapter 類別(如 MouseAdapter、WindowAdapter)僅覆寫需求方法,避免空實作。
  • getActionCommand() 優於文字比對: 為按鈕設定命令字串(setActionCommand),邏輯判斷更穩健。
  • isPopupTrigger() 跨平台一致性: 必須在 mousePressed 與 mouseReleased 皆檢查,因平台觸發時機不同。
  • 座標系區分: getPoint() 相對元件;getLocationOnScreen() 相對螢幕(Java 1.6+)。
  • 鍵盤事件三階段: keyPressed → keyTyped → keyReleased;唯有 keyTyped 可取得合成字符(含修飾鍵影響)。

註冊範例

button.addActionListener(e -> {
    String cmd = e.getActionCommand();
    if ("save".equals(cmd)) saveData();
    else if ("cancel".equals(cmd)) cancelDialog();
});

frame.addWindowListener(new WindowAdapter() {
    @Override public void windowClosing(WindowEvent e) { System.exit(0); }
});

熟練掌握事件模型細節,是構建流暢、健壯 Swing 應用的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved