why "itemStateChanges" isn't triggered, i tried to put it in the inner class "ButtonHandler" and also in "RadioButtonHandler" Im having troubles with it, what is the right way to do it? I want to trigger and check the marked JRadioButtons after the user click the "check" button.
ButtonHandler
is implemented with ActionListener
only:
public class ButtonHandler implements ActionListener{}
The itemStateChanged(ItemEvent)
function belongs to ItemListener
. This function is triggered if state of a source component to which this listener is registered gets changed. So implement the ItemListener
. However, one more thing to note, that JButton
doesn't respond to ItemListener
but JRadioButton
will. Because this Item
events are fired by components that implement the ItemSelectable
interface. Some example of such components are: check boxes, check menu items, toggle buttons and combo boxes including Radio Buttons as mentioned above.
What is the right way to check which button was clicked, i feel like comparing the strings is wrong programming. Maybe using an ID
Well using the event source function: e.getSource()
, check whither the type of the source is your expected type and cast it to appropriate type. And then you can use getName(String)
function and check the name you were expecting. Of-course you should assign the name using setName(String)
after initialization of component. Or using the component reference directly if it is declared in the Class context and you have direct access to the component.
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBox)
{
JCheckBox checkBox = (JCheckBox)e.getSource();
if(checkBox.getName().equals("expectedName"))
; // do my thing
}
}
How should i make a "reset" button(start over), i want to uncheck all radio buttons and run the constructor once again.
Well you are working with ButtonGroup
. And ButtonGroup
has a nice function: clearSelection()
to help with whatever(I could not understand the part: run the constructor part) you want.
Edit: As you wanted me to see an ItemListener
implemented class, Yes i can see that But:
- i can not see that you have actually registered an instance of that class(
a1.addItemListener(handler);
) to any component before performing any action on the component to whichButtonHandler
is registered to:checkMe, refresh
- In addition to that, in this action performed function, you are checking with
action command, which you haven't even set with
JButton.setActionCommand(String)
function. You should not assign a (Item)listener depending on event-occurrence of another (Action)listener.
Tutorial: