Question

My java swing app has some AbstractActions that are used in both JMenuItems and JButtons. I want to put some of them in a JToolbar inside a JButton, but I only want the icon to show, not the text. Is there a best practices way to do this?

Was it helpful?

Solution

easiest is to add the shared action to the toolBar, this will hide the text automatically:

Action sharedAction = new AbstractAction("some text") {
    ....
} 
sharedAction.putValue(Action.SMALL_ICON, someIcon);
myToolBar.add(sharedAction);
myNormalButton.setAction(sharedAction);

If for some reason you want to create the button in the toolBar manually, you have to configure its hideActionText property to true before adding the button to the toolbar

JButton manual = new JButton(sharedAction);
manual.setHideActionText(true);
myToolBar.add(manual);

Update

for the inverse requirement, solved in another answer, do the inverse, that is set the property to false:

AbstractButton button = myToolBar.add(sharedAction);
button.setHideActionText(false);

The advantage over creating and adding a JButton is to have the button configured as appropriate for a JToolBar with all internal listeners in place.

OTHER TIPS

You can set the value for the key Action.NAME to null or an empty String.

putValue(Action.NAME, null);

Addendum: As a convenience to users, put the previous string in Action.SHORT_DESCRIPTION, where it will become the button's toolTipText.

In my case I observed that if I just add the action to the JToolBar the text does not appear, so make sure you're putting the action in a JButton.

JToolBar tb = new JToolBar();
tb.add(new JButton(sharedAction));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top