java - 您将要为 Java 应用程序中的按钮加载的图像放在哪里?

标签 java image swing button icons

如果我不使用 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/

相关文章:

java - JPopupMenu 打开时开始鼠标拖动?

javascript - 如何在javascript中创建带有图像和标题的按钮

java - 单选按钮位置

java - 尝试将 ResultSet 打印为 PDF 文件

java - 查找 Java 字符串中出现的字符

html - "Crop"使用 CSS 的照片

android - 在 (`Drawable` 的 android `bitmap` 中使用图像的有效方法)

java - 如何最大化 JFrame

java - 如何获取 GridLayout 中元素的 X 和 Y 索引?

java - 遍历 POJO 属性并将其设置为另一个对象