If I have an application with 240 JButtons, what would be the best way to manage the tracking of events? What would be a better alternative to writing the following over two-hundred times:
if (e.getSource() == btn[0]) {}
If I have an application with 240 JButtons, what would be the best way to manage the tracking of events? What would be a better alternative to writing the following over two-hundred times:
if (e.getSource() == btn[0]) {}
You can separate behavior from data. For a group of buttons with similar behavior, write only one listener for the action performed. Then store data in the JButton instance, either with setTag()/getTag() or by extending and adding the data in a custom subclass.
The listeners will be responsible for basic tasks such as changing JButton ImageIcon's.
All listeners will contain a reference to the component that generated the event.
So you can do something basic like:
ActionListener al = new ActionListener(
{
@Override
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
button.setIcon(...);
}
});
for (int i = 0; i < 240; i++)
{
JButton button = new JButton(...);
button.addActionListener( al );
panel.add( button );
}