1

I'm creating a GUI with SWING. Some of the buttons have a custom Action attached. My code looks like:

JButton btn = new JButton(text);
btn.setAction(new MyAction());

My action class constructor does:

super(text) //set the label of the button

My question is: since it seems wrong to me repeat the same parameters (the text) two times, how should i handle this? Create the button with no text and let the action set the text (maybe as a constructor parametere)? What is the correct way to handle this? Thanks

Enoon
  • 421
  • 4
  • 17
  • What are you asking. Setting an `Action` as model of a `JButton` will adjust the text of the `JButton` to match the name of the `Action`. So I do not see why you would have to repeat the text twice – Robin Nov 06 '12 at 16:25
  • `JButton btn = new JButton(new MyAction());` or if there is also a menu item, `Action action = new MyAction(); JButton btn = new JButton(action); menu.add(action);` – Andrew Thompson Nov 06 '12 at 16:25
  • I was asking for the most elegant and clear way to do it; basically what Andrew said, thanks. – Enoon Nov 06 '12 at 16:35
  • +1 for aspiring to [DRY](http://en.wikipedia.org/wiki/Don't_repeat_yourself). – trashgod Nov 06 '12 at 19:19

1 Answers1

2

Use the AbstractAction(String name) constructor that includes the name. Several examples are cited here.

Addendum: As @MadProgrammer comments, Action.NAME is an available key for putValue(). This related example illustrates putValue() for other properties.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045