1

以下の画面がありました: ここに画像の説明を入力

public BillSummaryScreen() {
   ..........
   ShortcutKeyUtils.createShortcutKey(this, KeyEvent.VK_ENTER, "enterShortcut", new EnterAction());

}

public static void createShortcutKey(JComponent panel, int keyEventCode, String actionShortcutName, AbstractAction action){
        InputMap inputMap =  panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        inputMap.put(KeyStroke.getKeyStroke(keyEventCode, 0), actionShortcutName);
        ActionMap actionMap = panel.getActionMap();
        actionMap.put(actionShortcutName, action);
    }

private class EnterAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("EnterAction");
        }

    }

検索ボタンがクリックされるように「ENTER」キーを押したい。しかし、(マウスで)1つのコンボボックスにフォーカスしてENTERを押すと、アクションが機能しませんでした

4

1 に答える 1

1

ENTER バインディングのみに関心がある限り、検索ボタンをルートペインのデフォルト ボタンとして定義することを検討してください。これにより、コンボ ボックスの入力がボタンのアクションに自動的に渡されます。

JButton searchButton = new JButton(searchAction);
frame.getRootPane().setDefaultButton(searchButton);

任意のバインディングを渡すことは可能ですが、ユーザビリティの観点からは少し難しいです (コンポーネントにバインドされたアクションとウィンドウ バインディング内のアクションの両方が発生すること本当に望んでいますか?)。視点。後者を解決するには、基本的に、以下の MultiplexingTextField で行われるように、バインディング メカニズムをだまして keyStroke に関心がないと信じ込ませるカスタム コンポーネントが必要です。

JComboBox に対してこれを行うには、独自の障害があります。このようなカスタム textField を使用するカスタムのomboBoxEditor を実装する必要があります。エディターは LAF によって制御されているため (ほぼそれぞれの外観が異なります)、LAF ごとにカスタム エディターが必要になります (ソースと c&p を確認してください :-)。

/**
 * A JTextField that allows you to specify an array of KeyStrokes that
 * will have their bindings processed regardless of whether or
 * not they are registered on the JTextField itself. 
 */
public static class MultiplexingTextField extends JTextField {
    private KeyStroke[] strokes;
    private List<KeyStroke> keys;
    MultiplexingTextField(int cols, KeyStroke... strokes) {
        super(cols);
        this.keys = Arrays.asList(strokes);
    }

   @Override
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                                        int condition, boolean pressed) {
        boolean processed = super.processKeyBinding(ks, e, condition,
                                                    pressed);

        if (processed && condition != JComponent.WHEN_IN_FOCUSED_WINDOW
                && keys.contains(ks)) {
            // Returning false will allow further processing
            // of the bindings, eg our parent Containers will get a
            // crack at them.
            return false;
        }
        return processed;
    }

}
于 2013-11-11T12:52:29.677 に答える