簡體   English   中英

設置鍵綁定以執行與我的動作偵聽器中相同的操作

[英]Setting a key-binding to perform the same action as in my action listener

我有一個附加到ActionListener的JButton,但我還想為按鈕添加一個快捷鍵以使用戶更友好。 比如,用戶可以單擊按鈕,程序執行某些功能“f”,或者用戶也可以按鍵盤上的“Enter”執行相同的功能f。 所以這就是我的代碼的主旨

private JButton button;

public static void main(String[] args){
    Action buttonListener = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
                //Perform function f    
         }
    };

button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"),
                        "test");
button.getActionMap().put("test",
                         buttonListener);

button.addActionListener(new OtherListener());
}

private class OtherListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        //Perform function f
    }
}

看起來有點乏味,不得不添加Action和ActionListener來做同樣的事情。 也許我沒有看到它,但有沒有辦法減少代碼,所以我可以消除Action並只使用actionListener? 我在考慮在getActionMap()。put()方法中切換buttonListener參數,但該方法只接受Action類型。

Action擴展了ActionListener ,因此您應該能夠定義單個Action並在需要ActionListener任何地方使用它。

例如

public static void main(String[] args){
    Action buttonListener = new Action() {
         public void actionPerformed(ActionEvent e) {
                //Perform function f    
         }
    };
    button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke("ENTER"), "test");
    button.getActionMap().put("test", buttonListener);
    button.addActionListener(buttonListener);
}

JRootPane有一個方法setDefaultButton(...)可以做你想要的。 您需要從頂級容器中獲取根窗格,然后您可以調用此方法傳遞對JButton的引用,並且當在GUI上按下enter時它將執行其操作。 當你想到它時,這是有道理的,因為“輸入”是一個特殊的鍵,其行為應該是GUI的責任,而不是單個按鈕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM