Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action Listener on a radio button

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?

like image 302
agarwav Avatar asked Jul 03 '12 18:07

agarwav


People also ask

How do you add an action listener to a button?

We would like to handle the button-click event, so we add an action listener to the button b as below: b = new Button("Click me"); b. addActionListener(this); In the above code, Button b is a component upon which an instance of event handler class AL is registered.

How do you add an action listener to a button in Java?

To add the ActionListener to the JButton , we use the addActionListener() function, and in that method, we use the lambda approach. We use the parameter e that is an ActionEvent object, then call the buttonPressed() method.

What is an action listener?

ActionListener in Java is a class that is responsible for handling all action events such as when the user clicks on a component. Mostly, action listeners are used for JButtons. An ActionListener can be used by the implements keyword to the class definition.

What is the use of action listener interface?

Interface ActionListener The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method.


1 Answers

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);

        }
    });
like image 72
pbible Avatar answered Sep 29 '22 00:09

pbible