I've come across 2 different styles when adding button listeners in UI. I use SWT as example. But nonetheless I saw the similar code in J2ME, Flash Actionscript as well.
style 1:
b1.addSelectionListener(new SelectionListener()
{
public void widgetSelected(SelectionEvent e)
{
System.out.println("b1: ");
}
public void widgetDefaultSelected(SelectionEvent e)
{
System.out.println("Default selection");
}
});
b2.addSelectionListener(new SelectionListener()
{
public void widgetSelected(SelectionEvent e)
{
System.out.println("b2: ");
}
public void widgetDefaultSelected(SelectionEvent e)
{
System.out.println("Default selection");
}
});
style 2:
b1.addSelectionListener(this);
b2.addSelectionListener(this);
public void widgetSelected(SelectionEvent e)
{
if (e.getSource() == b1)
{
System.out.println(b1);
}
else if (e.getSource() == b2)
{
System.out.println(b2);
}
}
public void widgetDefaultSelected(SelectionEvent e)
{
System.out.println("Default selection");
}
Personally I prefer second style, because it gives me a centralize way to handle mouse event. Which style do you prefer? and why?