-1

嘿,所以我已将图像移至正确的工作空间文件夹(src),但我不断收到此错误消息.....

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at GUI.<init>(GUI.java:20)
    at main.main(main.java:4)

这是代码

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;

public class GUI extends JFrame {
    private JButton reg;
    private JButton custom;
    public GUI(){
        super("Welcome");
        setLayout(new FlowLayout());
        reg = new JButton("reg button");
        add(reg);

        Icon b = new ImageIcon(getClass().getResource("b.png"));
        Icon a = new ImageIcon(getClass().getResource("a.png"));
        custom = new JButton("Custom", b);
        custom.setRolloverIcon(a);
        add(custom);

        thehandler handle = new thehandler();
        reg.addActionListener(handle);
        custom.addActionListener(handle);

    }

    private class thehandler implements ActionListener{
        public void actionPerformed(ActionEvent event){
            JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
        }
    }

}


-----------------------

import javax.swing.JFrame;
public class main {
public static void main(String agrs[]){
    GUI page = new GUI();
    page.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    page.setSize(300,200);
    page.setVisible(true);
}
}
4

2 回答 2

3

您必须将图像放在包含 src 的文件夹中才能直接使用,而不是放在 src 本身中。

于 2013-08-02T17:21:48.403 回答
1

图片应该在Src->DefaultPackage->**File.java,FileMain.java,b.png,x.png 下可见;如果图像文件在 **Src->DefaultPackage-> 下不可见,则按F5按钮或只需右键单击包资源管理器并单击刷新,这将使您的图像出现在Src->DefaultPackage-> 中。

于 2013-08-25T12:14:59.530 回答