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]) {}
  • What does the listener do? – Code-Apprentice Apr 26 '17 at 13:48
  • Hi, I'm trying to make a tile-based game. The listeners will be responsible for basic tasks such as changing JButton ImageIcon's. – Jack Morgan Apr 26 '17 at 13:50
  • 1
    You probably want to give us more pertinent information on your problem and your code to get a better answer, but if it's a tile based game, then all the tile buttons can share the same single listener, and just have a mechanism within the listener to find out which tile/button in the grid was pressed, and then pass this information to the model. Again a more specific answer will likely require a more fleshed-out question. – Hovercraft Full Of Eels Apr 26 '17 at 13:57
  • Please have a look at answers to the following similar questions [question/answer 1](http://stackoverflow.com/a/19216827/522444), [question/answer 2](http://stackoverflow.com/a/35592581/522444), [question/answer 3](http://stackoverflow.com/a/7016492/522444) (this one's mine!), [question/answer 4](http://stackoverflow.com/a/41072158/522444) (another more recent similar one by me). – Hovercraft Full Of Eels Apr 26 '17 at 14:05

2 Answers2

2

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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

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 );
}
camickr
  • 321,443
  • 19
  • 166
  • 288