如何将图像添加到 JButton

新手上路,请多包涵

我正在尝试将图像添加到 JButton,但我不确定我缺少什么。当我运行以下代码时,按钮看起来与我创建它时没有任何图像属性完全相同。 Water.bmp 位于我的项目文件夹的根目录中。

 ImageIcon water = new ImageIcon("water.bmp");
    JButton button = new JButton(water);
    frame.add(button);

原文由 kevinstueber 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 483
2 个回答

我认为您的问题出在图像的位置。你应该把它放在你的源代码中,然后像这样使用它:

   JButton button = new JButton();
  try {
    Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
    button.setIcon(new ImageIcon(img));
  } catch (Exception ex) {
    System.out.println(ex);
  }

在此示例中,假设图像位于 src/resources/ 文件夹中。

原文由 Rogach 发布,翻译遵循 CC BY-SA 3.0 许可协议

@罗加奇

您可能想添加:

 // to remote the spacing between the image and button's borders
button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
button.setBackground( ... );
// to remove the border
button.setBorder(null);

原文由 ungalcrys 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题