Lt Lobster
Lt Lobster

Reputation: 41

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

Upvotes: 0

Views: 633

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Just FYI, this is what I mean by a small-"ish" compilable runnable program that demonstrates a problem. Here I demonstrate not adding action listeners or any listeners to JRadioButtons but rather adding a single listener to a JButton (actually an AbstractAction which is like an ActionListener on steroids). This uses ButtonGroup objects to allow only one JRadioButton to be selected per group, and to allow the code to query which button was selected. The ButtonGroup will return the "model" for the selected JRadioButton, and then we extract the actionCommand String from this model:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class MyMcve extends JPanel {
    private static final String[] SHAPES = {
        "Circle", "Square", "Triangle"
    };
    private static final String[] COLORS = {
        "Red", "Orange", "Yellow", "Green", "Blue" 
    };
    private ButtonGroup shapeButtonGroup = new ButtonGroup();    
    private ButtonGroup colorButtonGroup = new ButtonGroup();

    public MyMcve() {
        JPanel shapesBtnPanel = new JPanel(new GridLayout(0, 1));
        shapesBtnPanel.setBorder(BorderFactory.createTitledBorder("Shapes"));
        for (String shape : SHAPES) {
            JRadioButton radioButton = new JRadioButton(shape);
            radioButton.setActionCommand(shape);
            shapeButtonGroup.add(radioButton);
            shapesBtnPanel.add(radioButton);
        }
        JPanel colorsBtnPanel = new JPanel(new GridLayout(0, 1));
        colorsBtnPanel.setBorder(BorderFactory.createTitledBorder("Colors"));
        for (String color : COLORS) {
            JRadioButton radioButton = new JRadioButton(color);
            radioButton.setActionCommand(color);
            colorButtonGroup.add(radioButton);
            colorsBtnPanel.add(radioButton);
        }

        JPanel bothButtonPanel = new JPanel(new GridLayout(1, 2));
        bothButtonPanel.add(shapesBtnPanel);
        bothButtonPanel.add(colorsBtnPanel);


        JButton getSelectionBtn = new JButton(new GetSelectionAction("Get Selection"));
        JPanel btnPanel = new JPanel();
        btnPanel.add(getSelectionBtn);

        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        setLayout(new BorderLayout());
        add(bothButtonPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.PAGE_END);
    }

    private class GetSelectionAction extends AbstractAction {
        public GetSelectionAction(String name) {
            super(name);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String shapeSelection = "";
            String colorSelection = "";
            ButtonModel shapeModel = shapeButtonGroup.getSelection();
            if (shapeModel != null) {
                shapeSelection = shapeModel.getActionCommand();
            }

            ButtonModel colorModel = colorButtonGroup.getSelection();
            if (colorModel != null) {
                colorSelection = colorModel.getActionCommand();
            }

            System.out.println("Selected Shape: " + shapeSelection);
            System.out.println("Selected Color: " + colorSelection);
        }
    }

    private static void createAndShowGui() {
        MyMcve mainPanel = new MyMcve();

        JFrame frame = new JFrame("MCVE");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

Upvotes: 2

ricky3350
ricky3350

Reputation: 1738

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!

Upvotes: 3

Related Questions