How to avoid redundancy in button text while using custom action Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to avoid redundancy in button text while using custom action without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

Answer

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.

We are here to answer your question about How to avoid redundancy in button text while using custom action - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji