I have a Jbutton that when pressed creates another button and the new button is added to the panel. How to I add an actionListener to the new button?
For example:
One way would be to have a inner class containg the listener:
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button)
{
JButton newButton = new JButton("ahah");
newButton.addMouseListener(new yourListener());
}
}
//add this class as a inner class
public class aListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
JButton buttonReference=(JButton)e.getSource(); // you want this since hardcoding the name of the button is bad if you want listeners for more then one button
buttonReference.setText("lala");
}
}
This will create a instance of yourListener, and add that to the button when you click it