Search code examples
javaswingradio-buttonlistenerjradiobutton

My JRadioButton won't work with my action listener


So I'm making a program that finds out the surface area and the volume of polyhedrons, so I need to use JRadioButtons to let the user select what shape they want, if they want SurfaceArea or Volume, and stuff like that.

However, I ran into a problem that requires me to make something run every time that a new button is clicked.

When I added an actionListener() to my JRadioButton, the actionPerformed() method didn't even run. Is there something that I am missing?

I want my actionPerformed()method to run.

width.addActionListener(ral);
height.addActionListener(ral);
length.addActionListener(ral);
slantHeight.addActionListener(ral);
radius.addActionListener(ral);
displayAnswer.addActionListener(ral);


public void actionPerformed(ActionEvent a) {
    System.out.println("Changed Radio Button: " + a.getSource());
}

Solution

  • From How to Write an Item Listener (emphasis mine):

    Item events are fired by components that implement the ItemSelectable interface. Generally, ItemSelectable components maintain on/off state for one or more items.

    Since a radio button fits this description, ItemListener would be a more suitable listener to use; try that instead.

    Hope this helps!