Custom ToolBar with Java Swing for Desktop - java

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

Related

Read external Files with GlassFish / Vaadin?

I would like to make .txt-files accessible for my VaadinApp on a GlassfishServer.
Lets say I have a .txt-file, its content is 12345.
Now, when I click a button on my Vaadin StartPage, I would like to show the Data that has been written into this .txt-file.
I know how Java Input/Output is working but I have no clue how to make those files accessible for my VaadinApplication running on Glassfish 4.1.2.
Is there a folder I can put the .txt-file in, or how would I access the file?
Thanks
There is component named Label is available in Vaadin.
So that, the values which needs to be shown on the screen can be set as a caption/value for that object.
This can be done either through constructor or setter in that object.We will set the value through the setter as we need to display the value, once the button is clicked. That can be done like this.
Label sampleLabel = new Label();
sampleLabel.setContentMode(com.vaadin.shared.ui.ContentMode.HTML);
Now we will see how this can be added to the label, when a button is clicked.
Button sampleButton = new Button("Click");
sampleButton.addClickListener(event -> sampleLabel.setValue(<call the method that reads data from the text file>));
I hope this will be helpful.
Note: Basically you can place the file anywhere in the system.
But most preferred way.
If you are using maven to build the project, place the files in the resource folder.(src/main/resources)

Jar won't display Images

I have problem with Image Icons. I know that this have been asked before, but I can't figure out how to fix this, becouse I think my problem is different. When I launch app with eclipse, all works. But when I make it runnable jar, it won't show images.
Some code of my ImagesHolder Class :
package Clicker;
import javax.swing.ImageIcon;
public class ImagesHolder {
final public ImageIcon AccessoriesIcon = new ImageIcon("Images/Part_Accessories.png");
final public ImageIcon BodyIcon = new ImageIcon("Images/Part_Body.png");
final public ImageIcon BrakesIcon = new ImageIcon("Images/Part_Brakes.png");
final public ImageIcon CoolingIcon = new ImageIcon("Images/Part_Cooling.png");
final public ImageIcon ElectronicsIcon = new ImageIcon("Images/Part_Electronics.png");
final public ImageIcon EngineIcon = new ImageIcon("Images/Part_Engine.png");
final public ImageIcon ExaustIcon = new ImageIcon("Images/Part_Exaust.png");
final public ImageIcon FuelIcon = new ImageIcon("Images/Part_Fuel.png");
final public ImageIcon InteriorIcon = new ImageIcon("Images/Part_Interior.png");
final public ImageIcon SteeringIcon = new ImageIcon("Images/Part_Steering.png");
final public ImageIcon SuspensionIcon = new ImageIcon("Images/Part_Suspension.png");
final public ImageIcon TransmissionIcon = new ImageIcon("Images/Part_Transmission.png");
final public ImageIcon TiresIcon = new ImageIcon("Images/Part_Tires.png");
And If I make Images as URL, i can't reset image icons, like here (I have Labels and I want to change label icon)
Labels example :
public JLabel AccessoriesLVL1Label = new JLabel(ImagesHolder.LockedIcon);
AccessoriesLVL1Label.setHorizontalTextPosition(JLabel.CENTER);
AccessoriesLVL1Label.setVerticalTextPosition(JLabel.BOTTOM);
AccessoriesLVL1Label.setText("<html>Accessories LVL 1<br>" + "Count: " + Part.parts[1]);
And change :
if(CarMain.main[5] >=1){
jbtnSellAccessoriesLv1.setEnabled(true);
Labels.AccessoriesLVL1Label.setIcon(ImagesHolder.AccessoriesIcon);
}
Edited:
If I this :
final public ImageIcon MoneyIcon = new ImageIcon("Images/Money.png");
Make as :
URL MoneyIcon = ImagesHolder.class.getResource("/Money.png");
I get error in this line:
Labels.MoneyLabel.setIcon(ImagesHolder.MoneyIcon);
Error :
The method setIcon(Icon) in the type JLabel is not applicable for the arguments (URL)
There is an alternative for getting images from jar file:
Ideal way would be to have a resource directory under your project root and include it into the list of source code directories. This will result in all images there being copied into the JAR. If you make a sub directory there, resources/image, then you'll end up with a JAR that has an image directory. You access those images through the classloader:
classloader.getResourceAsStream("/image/image1.jpg");
or,
classloader.getResource("/image/image2.jpg");
Refer this link for in detail example.
Well, to sum up the previously given answers:
I guess a potential solution would be to use classloader as Dark Knight proposed. Furthermore you just need to create a new ImageIcon before setting it.
URL MoneyIcon = ImagesHolder.class.getResource("/Money.png");
Labels.MoneyLabel.setIcon(new ImagesIcon(ImagesHolder.MoneyIcon));
Because if you look through your code again, I guess it somewhat makes sense it does not work. I mean you want to set an ImageIcon, yet the last thing you have is an URL object. That this must throw an error should make sense. Yet as Andrew Thompson already said: You can construct an ImageIcon from that URL as displayed/explained above.
And since you also explained that you had issues with the directories (getting the structure from source to compiled) I want to add some links for further reading: If you just use 'plain' Java (no build tools) maybe this link can help: Copying data files upon build in Java/Eclipse. It is mainly written for Eclipse, but I guess most other IDEs should provide similar options.
From my current projects I could also recommend to use a tool like Maven. For smaller projects it might be a little over the top, but it takes of a lot of work (e.g. library handling, handling of resources like images etc.). These are just some parts that might be useful for you. If this is of interest for you I guess you will find lots of useful resources on the web since Maven (or other tools like Ant and Gradle) are quite commonly used.

Adding images in java [duplicate]

I have 6 JButtons on my GUI all have images on it,
when I compile and run the code, all images on JButtons show up perfectly
but in runnable JAR file, images on JButtons are not showing up.. how do I fix this problem?
I used this method in my code to show icons on JButtons
ImageIcon SettingsIc = new ImageIcon("bin/images/settings.png");
jb1 = new JButton(SettingsIc);
jb1.setFocusPainted( false );
//jb1.setBorderPainted(false);
jb1.setContentAreaFilled(false);
This is how my GUI looks when I compile my code in Eclipse
This is how my GUI looks after executing Runnable JAR file
This (as pointed out by a number of people)
ImageIcon SettingsIc = new ImageIcon("bin/images/settings.png");
Suggests that you are trying to load the images from the bin/images off the file systems. This is a relative path from the execution point of your application.
ImageIcon won't complain if the file does not exist.
If possible, you are better off embedding the resources within your Jar file (it will make it easier to deploy) and use something like getClass().getResource("/bin/images/settings.png") to load the images.
If possible, you should try using ImageIO.read(URL) to load your images, it will throw an exception if the resource pointed to by the File/URL does not exist (or is invalid).
Just keep the jar and images in the same folder and
keep
ImageIcon icon = new ImageIcon("image.jpg");
in the code

Unable to get image icon in runnable jar

I wrote a method in order to get icon for my swing:
public Icon getIcon(String iconName) {
Icon icon = null;
if(iconName.equals("NEXT")){
icon = new ImageIcon( getClass().getResource("resources/img/next.png" ) );
}
return icon;
}
but
icon = new ImageIcon( getClass().getResource("resources/img/next.png" ) );
goes in null pointer
I created a source folder "resources" and a folder "img" inside it with "next.png" icon
Where's the problem?
Thanks
For this to work, the resources folder should be in the same folder as the folder corresponding to the package of this.getClass(). To start from the root of the classpath, use getClass().getResource("/resources/img/next.png"). (with a leading /)
so, I found the right method:
public static ImageIcon getImageIcon(String iconName) {
ImageIcon imageIcon = null;
if(iconName.equals("DOWNLOAD")){
imageIcon = new ImageIcon(ImagesLocation.class.getResource("/img/download.png"));
}
return imageIcon;
}
with a "resources" source folder at the same level of the project and with an img folder inside (package styled)
ImagesLocation is a generic class containing this method
For those in need of help that have come across this page in Google - I wrote an answer in another StackOverflow question giving the best way to handle images in JAVA apps so that you can easily access the images for all image method types in Java:
This IS the best way to handle all images and icons in a JAR App.
Once you've zipped up all of your images and icons into its own JAR file - Configure your build path by adding the images JAR file into your libraries tab so that its now included in your classpath.
Then simply use the following 3x lines of code at the start of your constuctor to access any image you need for anything including a SystemTray image which doesn't accept the simple ImageIcon's as its main icon (weird I know). The 3x lines are:
URL iconUrl = this.getClass().getResource("/image-iconb.png");
Toolkit tk = this.getToolkit();
someimgicon = tk.getImage(iconUrl);
(someimgicon is just a constructor declared Image variable)
Now you can set a window icon as simply as:
setIconImage(someimgicon);
and at the same time use the same variable when setting the System TrayIcon by declaring:
trayIcon = new TrayIcon(someimgicon, "SystemTray Demo", popupMenu);
The above allows you to declare Images or ImageIcons easily and centrally without running the risk of not keeping image resources in the right place. It keeps it nice and tidy, with the JAR containing all your images automatically compiled at run time and distribution of your program.
As a bonus, once the JAR is registered in your classpath - you can keep adding any other images into the same JAR at any time without any fuss too - Everything just works and the added images are instantly available to your app.
Much better in my view.

path of an image in an eclipse project

I'm trying to display two pictures on my JFrame, the way I found was to use icons and JLabels, this seems pretty straightforward and I'm not having problems with this. But when it comes to locating the image I can't get it to work. I'm on a linux machine thus the forwardslash style. I created a folder called pics in my project which is called 399assig1.
ImageIcon icon1 = createImageIcon("/home/dsk03/ugrad/jeanbern/workspace/C291/workspace/399assig1/pics/fur-05.jpg","First");
this.label1 = new JLabel("Picture 1", icon1, JLabel.CENTER);
ImageIcon icon2 = createImageIcon("pics/fur.png","Second");
this.label2 = new JLabel("Picture 2", icon2, JLabel.CENTER);
this is the error I get
Couldn't find file: /home/dsk03/ugrad/jeanbern/workspace/C291/workspace/399assig1/pics/fur-05.jpg
Couldn't find file: pics/fur.png
if createImageIcon() is searching the CLASSPATH for the file, you'd need to add the root directory to the CLASSPATH. A better approach would be use a path that is relative to a directory that is already included in the CLASSPATH.
Like so:
%>CLASSPATH=$CLASSPATH;/home/dsk03/ugrad/jeanbern/workspace
then your call would be
ImageIcon icon1 = createImageIcon("399assig1/pics/fur-05.jpg", "MyIcon");

Categories