Event handling... inner classes or not? what do you recomend?
Me question is should you
use
JButton addbutton=new JButton("Add");
addbutton.addNewActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
...
}
});
or this
class Window implements ActionListener
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==addbutton)
{
...
}
if (e.getSource()==...
}
So when I would have say menu and 15 menuitems to listen, I would prefer the innerclass system becauses it somehow produces cleaner code, but it creates pretty much of those $1 $2 files... will it be a problem?
>I prefer to use inner classes since it makes clean code.
>However I prefer to define one innerclass per source
>type and not the getSource() trick. This gives a clean
>separation of responsability. You can use the same
>innerclass for different sources if the reaction should
>be the same for different user inputs.
you mean something like this:
Button b1=new Button("Edit1");
Button b2=new Button("Edit2");
b1.addActionListener(new InnerClass(b1));
b2.addActionListener(new InnerClass(b2));
...
That's what I do, I have a separate inner class for each button. You could have one class that handled actions for several buttons, but then the class would contain lots of code like
if (e.getSource() == addButton)...
and one of the rules-of-thumb of object-oriented processing is that if you find switch-like constructs in your code, that's a hint that you should break it into separate classes... hence what I do. Just as filipicom said.