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 theAbstractActionconstructorpublic 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
Actionis 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 aJMenuItemin aJMenuthat 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
JMenuItemit would put both the String and the icon.Then just add the
Actionto 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/imagesdirectory 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
JMenuItemand theJToolBarbutton share the same action. Notice that in theJToolBarall I have to do is add theAction, I don't need to create a button for it. TheJToolBarautomatically 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!