如果我不使用 guiformbuilder 创建应用程序,我有一个包 com.supercorp.killerapp,其中有一个包(com.supercorp.killerapp.views):
- 如何在 View 目录中的 JInternalFrame 上设置按钮的图标?
- 一般来说,如何访问不同文件夹中的图像?
- 我的所有图像都应该包含在单独的文件夹中吗?
我使用的语法是:
JButton iconButton = new JButton(new ImageIcon("page_delete.png"));
该按钮未显示图像。
最佳答案
我将包含我的应用程序的 jar 放入名为 com.example.GreatApp.resources
的包中,然后使用以下命令加载它:
getClassLoader().getResourceAsStream(
"com/example/GreatApp/resource/icon.png");`
更新。完整示例
/**
* Creates and returns an ImageIcon from the resource in jar.
* @param location resource location in the jar,
* like 'com/example/GreatApp/res/icon.png' or null if it was not found.
*/
public ImageIcon createImageIconFromResource(String location)
throws java.io.IOException {
java.io.InputStream input = getClassLoader().getResourceAsStream(
location);
// or throw an ioexception here aka `file not found`
if(input == null) return null;
return new ImageIcon(ImageIO.read(input));
}
关于java - 您将要为 Java 应用程序中的按钮加载的图像放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4400908/