[java] OO Styles

Started by
11 comments, last by Jim_Ross 23 years, 11 months ago
Try this instead:

public static final String OK_COMMAND = "OK";
...
JButton jb = new JButton(getLocalizedCommand(OK_COMMAND));
jb.addActionListener(this);
jb.setActionCommand(OK_COMMAND);
...
public void actionPerformed(ActionEvent evt)
{
if (evt.getActionCommand().equals(OK_COMMAND))
{
...
}
}

You''d write the "getLocalizedCommand" method would get the localized String for the button label, based on the action command OK_COMMAND. This allows for localization, and you can also add the action command to other controls, if need be. It also allows you to use a button with an icon instead of text, if you wanted to. Basically, the idea is to remove the functionality from the presentation of the functionality. That way you can change the label without changing anything else (which is why Action classes are so cool, but that''s another story).

Still, for simple, one-shot things like dialog buttons, an anonymous inner class is sometimes the better way to go, because that way you don''t have to do ANY testing to see what control generated the event.
I am a Jedi, like my father before me
Advertisement
Hey, but doesn''t e.getActionCommand(); do that string comparison thing or am I missing the trick?
Sorry, but I had error in my code, because the event which makes my custom button click in mouse released section got accidentally deleted when I made some arrangements, but still, doesn''t that e.getActionCommand() thing work with awt buttons when eventing them by label?

Time comes, time goes and I only am.

This topic is closed to new replies.

Advertisement