I am trying to add a icon to a toolbar but what is the best place to put it in? My desktop or should I make a new file in the project file or add all the pictures in because it is not showing and this is my code:
JToolBar toolBar = new JToolBar();
String[] iconFiles = {"pen-icon","",""};
String[] buttonLabels = {"New","Open","Save"};
icon = new ImageIcon[iconFiles.length];
Obutton = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; ++i) {
icon[i] = new ImageIcon(iconFiles[i]);
Obutton[i] = new JButton(icon[i]);
Obutton[i].setToolTipText(buttonLabels[i]);
if (i == 3)
toolBar.addSeparator();
toolBar.add(Obutton[i]);
}
I would use an
Action
. Here is theAbstractAction
constructorpublic AbstractAction(String name, Icon icon)
- Creates an Action with the specified name and small icon.Parameters:
name - the name (Action.NAME) for the action; a value of null is ignored
icon - the small icon (Action.SMALL_ICON) for the action; a value of null is ignored
The benefit of using an
Action
is that is can be reused for components with similar purposes. So say you want to have an icon button in the toolbar to open a file, and also have aJMenuItem
in aJMenu
that also opens a file. They could share the same action, thus sharing the same icon, action command, and action to perform.The above will automatically put the icon for you, but not the String. In a
JMenuItem
it would put both the String and the icon.Then just add the
Action
to the tool bar.See more at How to use Actions
To answer you real question, as @MadProgrammer noted, you should be loading your images as an embedded resource, using
where the
/resources/images
directory is in thesrc
, andgetResource()
returns a URL. Upon build, your IDE should copy the files into the class path for you.You'll come to find that when using a file from the file system, will not work upon time of deployment
Here's an example, where the
JMenuItem
and theJToolBar
button share the same action. Notice that in theJToolBar
all I have to do is add theAction
, I don't need to create a button for it. TheJToolBar
automatically makes it a button, without the action commandI use this "open.gif" from the below file structure and use
Here's the result
Here's the code. Enjoy!