1

I am trying to code very simple Java program - if the shape is fill and click on particular button is made than the message will popup. On the other hand, if the fill is not selected it will show different messages.

fill.addItemListener(new ItemListener());
rect.addActionListener(new ButtonListener());

And the action event I have written is:

private class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==fill) {
            if(e.getSource()==rect) {
                JOptionPane.showMessageDialog(null,"Shojibur");
            }
            else {
                JOptionPane.showMessageDialog(null,"Checking");
            }
        }
    }
}
dic19
  • 17,821
  • 6
  • 40
  • 69
Jahidul Islam
  • 29
  • 2
  • 7
  • 2
    Hint: `if(e.getSource()==rect)` won't ever be reached and `true` at the same time. Check your `if` block. Besides you add the action lsitener to `rect` radio button but not to `fill` radio button. Consequently `fill` can't be the action event source → the action listener doesn't show any message. – dic19 Nov 21 '14 at 15:38

1 Answers1

0

In your case you don't need the ItemListener for the JRadioButton. On button click you can check if the radio button is selected or not using

radioButton.isSelected()

and then show appropriate messages.

Example

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class RadioButtonTest extends JFrame implements ActionListener
{

    private JRadioButton radio;
    private JButton button;

    public RadioButtonTest()
    {
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        radio = new JRadioButton("Select Me!!");

        button = new JButton("Click Me!!");
        button.addActionListener(this);

        add(radio, BorderLayout.CENTER);
        add(button, BorderLayout.PAGE_END);

        pack();
        setVisible(true);
    }

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

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == button)
        {
            if (radio.isSelected())
                JOptionPane.showMessageDialog(this, "Selected.");
            else
                JOptionPane.showMessageDialog(this, "NOT selected!!");
        }
    }

}
Community
  • 1
  • 1
always_a_rookie
  • 4,515
  • 1
  • 25
  • 46