简体   繁体   English

JButton ImageIcon不起作用

[英]JButton ImageIcon not working

So im trying to get a specified image as the "look" of the Jbutton but it just isnt working. 因此,我试图获得指定图像作为Jbutton的“外观” ,但它不起作用。 any ideas? 有任何想法吗?

The code: 编码:

JButton btnClose = new JButton("Close");
    try {
        Image img = ImageIO.read(Window.class.getResource("resources/quit_button.bmp"));
        btnClose.setIcon(new ImageIcon(img));
      } catch (IOException ex) {
      }

btnClose.setVisible(true);
btnClose.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        frame.dispose();
    }
});

My image path is: C:\\Users\\ *User*\\workspace\\Pede\\pede_Exe\\resources\\quit_button.bmp 我的图像路径是:C:\\ Users \\ * User * \\ workspace \\ Pede \\ pede_Exe \\ resources \\ quit_button.bmp

"Isn't working" isn't a lot to go on, but my suspicion is that ImageIO is throwing an exception before setting the icon. “不工作”没有什么可继续的,但是我怀疑ImageIO在设置图标之前抛出了异常。 This is often (but not exclusively) because your path is wrong. 这通常是(但不是唯一的)因为您的路径是错误的。

First and foremost, print your stack trace. 首先,打印堆栈跟踪。 That should be, for you, 对你来说应该是

ex.printStackTrace();

in your catch block. 在您的捕获块中。 That stack trace is an arrow to the problematic code, and often has a plain-English explanation attached to it. 该堆栈跟踪是有问题的代码的箭头,并且通常附有简单的英语说明。 Get in the habit, you won't regret it. 养成这个习惯,您不会后悔的。

Second, see to it that you're looking in the right place for your image. 其次,要确保您正在寻找合适的图像位置。 The easiest way to do this can be found here: Find where java class is loaded from 可以在这里找到最简单的方法: 查找从何处加载Java类

As you can see, there are a lot of possibilities. 如您所见,有很多可能性。 If the path of your class, compounded with the path of your resource, is not a real thing, then ImageIO will not find your icon. 如果类的路径与资源的路径混合在一起不是真实的东西,则ImageIO将找不到您的图标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM