Another answer to this question. Change the small code from zalpha314 answer.
You can know which switch is selected by the text of this button, and you can also recognize it by the Action command. In the oracle demo code with a diagnosis of http://docs.oracle.com/javase/tutorial/uiswing/examples/components/RadioButtonDemoProject/src/components/RadioButtonDemo.java I learned how to use the action command.
First define two action commands
final static String ON = "on" final static String OFF = "off"
Then add the action command to the buttons
JRadioButton enableButton = new JRadioButton("Enable"); enableButton.setActionCommand(ON); JRadioButton disableButton = new JRadioButton("Disable"); disableButton.setActionCommand(OFF);
So, in actionPerformed you can get the action command.
public void actionPerformed(ActionEvent e){ String ac = e.getActionCommand(); if (ac.equals(ON)){ textField.setEditable(true); }else{ textField.setEditable(false); } }
The command action might be better if button.getText()
is a very long string.
source share