开发者

Context dependent keyboard bindings in java Swing

My application has a tree control on the left and a number of forms, tabs, etc. on the right. When a user presses Ctrl+F a search panel appears under the tree on the left, so the user can search the contents of the tree.

This is done via a menu accelerator.

However, when a certain tab is open on the right, I want Ctrl+F to open a search panel in this tab, to search inside the contents of the tab.

I have defined the key binding for this tab:

tab.getInputMap(WHEN_ANCESTOR_OF_开发者_运维知识库FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK), "showSearch");
tab.getActionMap().put("showSearch", showSearchAction);

showSearchAction above opens the search panel in the tab.

This does not work. Even when the tab is focused, Ctrl+F still opens the search panel under the tree.

How can I make the action that happens on Ctrl+F depend on the currently focused component?


tab.getInputMap(WHEN_FOCUSED)...

Edit:

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

public class TabbedPaneBinding extends JFrame
{
    public TabbedPaneBinding()
    {
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        JMenu menu = new JMenu( "File" );
        menuBar.add( menu );
        JMenuItem menuItem = new JMenuItem("Search");
        menuItem.setAccelerator( KeyStroke.getKeyStroke("control F") );
        menu.add( menuItem );

        menuItem.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println("do Search");
            }
        });

        add(new JTextField(10), BorderLayout.NORTH);

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Text Field", new JTextField(10));
        tabbedPane.addTab("CheckBox", new JCheckBox());
        add(tabbedPane);

        AbstractAction action = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println("tabbed pane Search");
            }
        };

        String keyStrokeAndKey = "control F";
        KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
//      InputMap im = tabbedPane.getInputMap(JTabbedPane.WHEN_FOCUSED);
        InputMap im = tabbedPane.getInputMap(JTabbedPane.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        im.put(keyStroke, keyStrokeAndKey);
        tabbedPane.getActionMap().put(keyStrokeAndKey, action);
    }

    public static void main(String args[])
    {
        TabbedPaneBinding frame = new TabbedPaneBinding();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize(200, 150);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜