JButton图像图标无法显示.png文件

3

我已经到处寻找解决方案,阅读了一些与此问题相关的类似帖子,但它们都没有对我起作用。

我正在尝试在JButton上显示图像“b.png”,当我滚动按钮时,图标会更改。

package GUI_JButton;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Gui extends JFrame {

    private JButton reg;
    private JButton custom;

    public Gui() {
        super("Title goes here");
        setLayout(new FlowLayout());

        reg = new JButton("reg button"); // create reg button
        add(reg); // add reg button to JFrame

        // initialize images
        Icon b = new ImageIcon(getClass().getResource("images/imageA.png"));
        Icon x = new ImageIcon(getClass().getResource("images/imageB.png"));

        custom = new JButton("custom button", b); // create custom button
        custom.setRolloverIcon(x);
        add(custom); // add button to JFrame

        HandlerClass handler = new HandlerClass();
        reg.addActionListener(handler);
        custom.addActionListener(handler);

    }

    private class HandlerClass implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(null,
                    String.format("%s", event.getActionCommand()));

        }

    }

}

图片存放在名为“images”的文件夹中,该文件夹与Gui.java文件和TESTMain.java文件同级,均位于src文件夹中。
我遇到的错误是来自Main的空指针异常。我已经尝试过
Icon b = new ImageIcon("images/imageA.png"); 

这段代码编译通过,但是图片无法显示。我也尝试了其他方法。
custom = new JButton("custom", new ImageIcon("images/imageA.png"));

并且

custom = new JButton("custom", new ImageIcon(getClass().getResource("images/imageA.png"));

我知道getClass().getResource()是首选的,因为图像需要与jar文件一起编译。
有没有关于如何显示我的图像的想法?

getResource("images/imageA.png") 改为 getResource("/images/imageA.png") - Andrew Thompson
1个回答

6

你的图片文件夹需要和已编译的 .class 文件放在同一个文件夹中,而不是和你的 .java 文件一起放在 src 中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接