Action Listener on a radio button

agarwav picture agarwav · Jul 3, 2012 · Viewed 79.7k times · Source

I would like to set editable option of a text box based on the selection of a radio button? How to code the action listener on the radio button?

Answer

pbible picture pbible · Nov 22, 2013

This is the solution that I would use in this case.

    //The text field
    JTextField textField = new JTextField();

    //The buttons
    JRadioButton rdbtnAllowEdit = new JRadioButton();
    JRadioButton rdbtnDisallowEdit = new JRadioButton();

    //The Group, make sure only one button is selected at a time in the group
    ButtonGroup editableGroup = new ButtonGroup();
    editableGroup.add(rdbtnAllowEdit);
    editableGroup.add(rdbtnDisallowEdit);

    //add allow listener
    rdbtnAllowEdit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            textField.setEditable(true);

        }
    });

    //add disallow listener
    rdbtnDisallowEdit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            textField.setEditable(false);

        }
    });