AbstractAction in JButton in JToolbar without text

icons, java, jbutton, jtoolbar, swing

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.

Problem

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?

Original source