3

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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user591568
  • 61
  • 2
  • 8

3 Answers3

11

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.

Community
  • 1
  • 1
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • 2
    +1 for `hideActionText()`, which is the [recommended](http://docs.oracle.com/javase/6/docs/api/javax/swing/Action.html) approach. – trashgod Apr 15 '12 at 16:51
1

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • ehhh ... no (at least as I understand the question: one Action with both text and icon shared by a plain button and a toolbar button showing both text and icon on the former and only the icon on the latter) – kleopatra Apr 15 '12 at 14:10
  • Ah, I though one `Action` with the same icon in both and text in neither. – trashgod Apr 15 '12 at 16:50
1

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));
dalvarezmartinez1
  • 1,385
  • 1
  • 17
  • 26
  • hmm .. so your goal is the opposite of the OP's, that is you _want_ the text to appear in the toolbar? – kleopatra Jul 30 '13 at 10:48
  • Exactly, hmm maybe I shouldn't have posted this here, as it might be confusing. I did not find anywhere how to add text and icon to the AbstractAction, after that I realized that if you add the AbstractAction to a JButton, you will see both, otherwise only the icon appears. – dalvarezmartinez1 Jul 30 '13 at 11:50