javaswingnavigationjradiobuttonarrow-keys

How To Disable Arrow Key Navigation For Java Swing JRadioButton?


I have some JRadioButtons in my Java Swing app. After I select one button, clicking on arrow keys will navigate thru all the buttons, but I need to use the arrow keys for other purposes, how to disable the default behavior so pressing on arrow keys won't navigate the radiobuttons ?

JRadioButton Button1=new JRadioButton("Button1");
JRadioButton Button2=new JRadioButton("Button2");
JRadioButton Button3=new JRadioButton("Button3");

Solution

  • When a JRadioButton is added to a ButtonGroup "Key Bindings" are added for the left, right, up and down arrow keys:

    You can remove the bindings with code like:

    InputMap im = button1.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    im.put(KeyStroke.getKeyStroke("RIGHT"), "none");
    im.put(KeyStroke.getKeyStroke("LEFT"), "none");
    

    Read the section from the Swing tutorial on Key Bindings for more information.