lundi 30 mars 2015

Get instance of an object from which an ActionListener is called [duplicate]


This question already has an answer here:




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




Aucun commentaire:

Enregistrer un commentaire