简体   繁体   中英

Custom ToolBar with Java Swing for Desktop

I have created a GUI with Java Swing and wanting to create a custom toolbar according to my modules. Below are the images am wanting to use:

在此处输入图片说明

These images are placed in the same level as the src folder within my application. I am aware that I can perhaps create a jar with these images so that I can easily access them from within my application but do not know how. I have spent hours trying to make this work.

Below is my GUI that I have created ad wanting to beautify with these images for the toolbar else create an array of labels that will act as a navigation but either approach I couldn't get it to work.

在此处输入图片说明

The code below was my last attempt on this:

 JToolBar toolbar1 = new JToolBar();

 ImageIcon client = new ImageIcon("clients.png");
 ImageIcon timesheet = new ImageIcon("timesheets.png");

 JButton clientTB = new JButton(client);
 JButton timesheetTB = new JButton(timesheet);

 toolbar1.add(clientTB );
 toolbar1.add(timesheetTB);

 add(toolbar1, BorderLayout.NORTH);

I even moved these images and placed them within the class that's calling them.

What could I be doing wrong, please help?

You have a look at the JavaDocs for ImageIcon(String) , the String value is "a String specifying a filename or path"

This is a problem, because your images aren't actually files, any more, they have been embedded within your application (typically within the resulting jar file) and no longer be treated like "normal files".

Instead, you need to use Class#getResource which searches the application's classpath for the named resource, something like...

// This assumes that the images are in the default package 
// (or the root of the src directory)
ImageIcon client = new ImageIcon(getClass().getResource("/clients.png"));

Now, I have a personal dislike for ImageIcon , because it won't tell you when the image is loaded for some reason, like it can't be found or it's the wrong format.

Instead, I'd use ImageIO to read the image

ImageIcon client = new ImageIcon(ImageIO.read(getClass().getResource("/clients.png")));

which will do two things, first, it will throw a IOException if the image can't be loaded for some reason and two, it won't return until the image is fully loaded, which is helpful.

See Reading/Loading an Image for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM