首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向JCheckBox添加KeyStroke

向JCheckBox添加KeyStroke
EN

Stack Overflow用户
提问于 2013-01-19 02:39:50
回答 1查看 240关注 0票数 0

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

我已经做了这部分代码,但它不能工作,有人能给我指出正确的方向吗?

代码语言:javascript
复制
    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]);
       }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-23 00:48:13

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

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

代码语言:javascript
复制
// 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]);
 }

顺便说一下:假设你的checkBoxes有动作(它们应该是:-),ToggleAction可以触发这些动作,而不是手动切换选择。此approach is used in a recent thread

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14405464

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档