0

I have an ActionListener class and Class with a JCheckBox in 2 separate files. The ActionListener checks if the checkbox is checked and changes the text next to the checkbox and deselects or selects the checkbox appropriately. What I can't figure out is how to get the instance of the checkbox to check if it is selected or not. I tried casting e.getSource to a JCheckBox but the compiler wouldn't allow it.

ActionListener Class:

public MyAL extends ActionListener
{
    public void actionPerformed(ActionEvent e) 
    {
        if (e.getActionCommand() == MyClass.ACT_CMD_!)
        {
            //if (checkbox is selected)
                //set checkbox text to "I'm Not Selected";
                //deselect the checkbox;
            //else
                //set checkbox text to "I'm Selected";
                //select the checkbox;
        }
    }
}

Class that has a JCheckBox:

public class MyClass 
{
    final static ACT_CMD_1 = "CHECK BOX";
    JCheckBox cb; 

    MyClass()
    {
        cb= new JCheckBox("I'm Not Selected");
        cb.addActionCommand(MyClass.ACT_CMD_1);
        cb.addActionListener(new MyAL());
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
yitzih
  • 3,018
  • 3
  • 27
  • 44
  • 2
    Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Mar 31 '15 at 01:52

1 Answers1

3

You can get the source of the event from the ActionEvent itself, for example...

Object obj = e.getSource();
if (obj instanceof JCheckBox) {
    JCheckBox cb = (JCheckBox)obj;
}

Also, don't use == to compare Strings in Java, instead you should be using String#equals or String#equalsIgnoreCase

if (ACT_CMD_1.equals(e.getActionCommand())) {
    //...
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366