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?
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.
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.
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.
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.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With