搜尋
首頁Javajava教程Java Swing 鍵處理:鍵綁定或鍵偵聽器 – 您應該選擇哪一個?

Java Swing Key Handling: Key Bindings or Key Listeners – Which Should You Choose?

Java Swing 中的鍵綁定與鍵偵聽器:綜合指南

鍵綁定和鍵偵聽器是處理用戶輸入事件的兩種方法來自Java Swing 應用程式中的按鍵。雖然按鍵偵聽器提供了一種簡單的方法來檢測按鍵,但按鍵綁定具有多個優點,包括:

  • 增強的響應能力:按鍵綁定不需要使用者點擊物件使其集中註意力,從而實現更快、更直觀的輸入處理。
  • 增強可維護性: 鍵綁定可以更輕鬆地停用、重新綁定和重新分配使用者操作,從而簡化維護和程式碼可讀性。

理解鍵綁定

按鍵綁定涉及兩個物件:

  • InputMap/將使用者輸入映射到操作名稱。
  • ActionMap:將操作名稱對應到操作。
按下某個鍵時,輸入映射會搜尋該鍵並找到操作名稱。然後在操作映射中搜尋操作名稱並執行操作。

實作鍵綁定

要建立單一鍵綁定,請使用下列結構:

myComponent.getInputMap().put("userInput", "myAction");
myComponent.getActionMap().put("myAction", action);

使用 WHEN_IN_FOCED_WINDOW InputMap

WHEN_IN_FOCUSED_WINDOW 的 InputMap 允許聚焦視窗中的多個元件同時接收輸入。例如,如果聚焦視窗中有多個坦克並希望它們接收輸入,請使用以下結構:

tank1.getInputMap(IFW).put(KeyStroke.getKeyStroke("W"), "move up");
tank2.getInputMap(IFW).put(KeyStroke.getKeyStroke("S"), "move down");
// ...
tankN.getInputMap(IFW).put(KeyStroke.getKeyStroke("T"), "fire");

重新綁定鍵

重新綁定使用KeyListener進行鍵:

obj1.getInputMap(IFW).remove(KeyStroke.getKeyStroke(oldKey));
// ...
obj1.getInputMap(IFW).put(KeyStroke.getKeyStrokeForEvent(ke),
                 obj1.getInputMap(IFW).get(KeyStroke.getKeyStroke(oldKey)));

程式碼範例

以下是示範鍵綁定的程式碼範例:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyGame extends JFrame {

    public MyGame() {
        // Do layout management, create objects, etc.
        JLabel obj1 = new JLabel();
        JLabel obj2 = new JLabel();

        // Set key bindings for object 1
        obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("UP"), "move up");
        obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DOWN"), "move down");
        obj1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control CONTROL"), "fire");
        obj1.getActionMap().put("move up", new MoveAction(1, 1));
        obj1.getActionMap().put("move down", new MoveAction(2, 1));
        obj1.getActionMap().put("fire", new FireAction(1));

        // Set key bindings for object 2
        obj2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("W"), "move up");
        obj2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("S"), "move down");
        obj2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("T"), "fire");
        obj2.getActionMap().put("move up", new MoveAction(1, 2));
        obj2.getActionMap().put("move down", new MoveAction(2, 2));
        obj2.getActionMap().put("fire", new FireAction(2));

        // Add objects to the JFrame
        add(obj1);
        add(obj2);
    }

    // Handle key rebinding
    public static void rebindKey(KeyEvent ke, String oldKey) {
        // Find and replace key binding
    }

    // Main method
    public static void main(String[] args) {
        new MyGame();
    }

    // Inner class for move action
    private class MoveAction extends AbstractAction {

        int direction;
        int player;

        MoveAction(int direction, int player) {
            this.direction = direction;
            this.player = player;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // Implement move logic
        }
    }

    // Inner class for fire action
    private class FireAction extends AbstractAction {

        int player;

        FireAction(int player) {
            this.player = player;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // Implement fire logic
        }
    }
}

結論

鍵綁定提供了一種強大而靈活的方式處理Java Swing應用程式中的使用者輸入事件。透過利用按鍵綁定,開發人員可以增強應用程式的回應能力、可維護性和可重複使用性。

以上是Java Swing 鍵處理:鍵綁定或鍵偵聽器 – 您應該選擇哪一個?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JVM性能與其他語言JVM性能與其他語言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生產性。 1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台獨立性:使用示例Java平台獨立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允許CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架構:深入研究Java虛擬機JVM架構:深入研究Java虛擬機May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM與操作系統有關嗎?JVM:JVM與操作系統有關嗎?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:寫一次,在任何地方跑步(WORA) - 深入了解平台獨立性Java:寫一次,在任何地方跑步(WORA) - 深入了解平台獨立性May 14, 2025 am 12:05 AM

Java實現“一次編寫,到處運行”通過編譯成字節碼並在Java虛擬機(JVM)上運行。 1)編寫Java代碼並編譯成字節碼。 2)字節碼在任何安裝了JVM的平台上運行。 3)使用Java原生接口(JNI)處理平台特定功能。儘管存在挑戰,如JVM一致性和平台特定庫的使用,但WORA大大提高了開發效率和部署靈活性。

Java平台獨立性:與不同的操作系統的兼容性Java平台獨立性:與不同的操作系統的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什麼功能使Java仍然強大什麼功能使Java仍然強大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

頂級Java功能:開發人員的綜合指南頂級Java功能:開發人員的綜合指南May 13, 2025 am 12:04 AM

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器