将KeyStroke添加到JCheckBox

时间:2013-01-18 18:39:50

标签: java swing keylistener jcheckbox keystrokes

我想将KeyStrokes添加到CheckBoxes组中,因此当用户点击1时,键击将选择/取消选择第一个JCheckBox。

我已经制作了这部分代码,但它没有用,有人能指出我正确的方向吗?

    for (int i=1;i<11;i++)
     {
           boxy[i]=new JCheckBox();
           boxy[i].getInputMap().put(KeyStroke.getKeyStroke((char) i),("key_"+i));  
           boxy[i].getActionMap().put(("key_"+i), new AbstractAction() {  
                 public void actionPerformed(ActionEvent e) {  
                     JCheckBox checkBox = (JCheckBox)e.getSource();  
                     checkBox.setSelected(!checkBox.isSelected());  
         }});
          pnlOdpovede.add(boxy[i]);
       }

1 个答案:

答案 0 :(得分:2)

问题是您使用类型为WHEN_FOCUSED的checkBox注册了绑定:它们仅对keyPressed时关注的特定复选框有效。

假设您想要独立于focusOwner切换选定状态,另一种方法是将keyBindings注册到checkBoxes的父容器,并添加一些逻辑来查找要切换其选择状态的组件:

// a custom action doing the toggle
public static class ToggleSelection extends AbstractAction {

    public ToggleSelection(String id) {
        putValue(ACTION_COMMAND_KEY, id);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Container parent = (Container) e.getSource();
        AbstractButton child = findButton(parent);
        if (child != null) {
            child.setSelected(!child.isSelected());
        }
    }

    private AbstractButton findButton(Container parent) {
        String childId = (String) getValue(ACTION_COMMAND_KEY);
        for (int i = 0; i < parent.getComponentCount(); i++) {
            Component child = parent.getComponent(i);
            if (child instanceof AbstractButton && childId.equals(child.getName())) {
                return (AbstractButton) child;
            }
        }
        return null;
    }

}

// register with the checkbox' parent
for (int i=1;i<11;i++)  {
       String id = "key_" + i;
       boxy[i]=new JCheckBox();
       boxy[i].setName(id);
       pnlOdpovede.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
           .put(KeyStroke.getKeyStroke((char) i), id);  
       pnlOdpovede.getActionMap().put(id, new ToggleSelection(id));
       pnlOdpovede.add(boxy[i]);
 }

BTW:假设你的checkBoxes有Actions(它们应该:-),ToggleAction可以触发那些Actions而不是手动切换选择。这approach is used in a recent thread