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:
For each button you can create it's own actionPerformed(...)
method, as described in the example below :
Do you mean to do this :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonAction
{
private JPanel contentPane;
private JButton updateButton;
private int count = 0;
private ActionListener updateListener = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
final JButton button = new JButton("" + count);
button.setActionCommand("" + count);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("My COMMAND is : " + event.getActionCommand());
}
});
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
contentPane.add(button);
contentPane.revalidate();
contentPane.repaint();
}
});
count++;
}
};
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("BUTTON ACTIONS");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
contentPane = new JPanel();
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
updateButton = new JButton("UPDATE GUI");
updateButton.addActionListener(updateListener);
frame.add(contentPane, BorderLayout.CENTER);
frame.add(updateButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new ButtonAction().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}