How to add an ImageIcon to a JToolBar

后端 未结 2 806
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 19:36

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

2条回答
  •  既然无缘
    2021-01-14 20:22

    Resources of this type are typically best contained within the application context (such as a jar file). This reduces the chances of someone tampering with it as it's much more time consuming to unpack, modify and repack a jar file then simply replace a file. It also reduces what you need to distribute as it becomes self-contained.

    These are known as embedded resources.

    Where you would put them within this context is up to up, many people use a "resources" folder to store these types of files, but sometimes, you may want something that is relative to the context of the class. It's up to you.

    This raises issues with loading these resources, as you can no longer reference them using something like File.

    In general you can use Class#getResource(String), which returns a URL or Class#getResourceAsStream(String) which returns a InputStream. This provides you with all you need to load these embedded resources.

    ImageIcon(String) expects the value to be a file reference, which means it won't work for embedded resources, but ImageIcon provides a constructor that takes a URL as a reference, this means you would need to use

    icon[i] = new ImageIcon(getClass().getResource(iconFiles[i]));
    

    To load your images.

    Based on your example, the images would need to be relative to the class (ie within a directory structure the same as your package structure). How you achieve this will depend on your development environment.

    Remember, you can also specify relative paths to getResource and even an absolute path in some contexts. An absolute path basic prefixes the elements of class path to the specified path when it searches for the resources.

提交回复
热议问题