문제

I want to add KeyStrokes to group of CheckBoxes ,so when user hits 1, keystroke will selected / deselected first JCheckBox.

I have made this part of code ,but its not working, can somebody point me into correct direction?

    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]);
       }
도움이 되었습니까?

해결책

The problem is that you registered the bindings with the checkBox' inputMap of type WHEN_FOCUSED: they will be effective only for that particular checkBox that is focused at the time of the keyPressed.

Assuming that you want to toggle the selected state independent of the focusOwner, an alternative is to register the keyBindings with the parent container of the checkBoxes and add some logic to find the component that's meant to have its selection state toggled:

// 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: assuming your checkBoxes have Actions (which they should :-), the ToggleAction could trigger those Actions instead of toggling the selection manually. This approach is used in a recent thread

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top