这个小程序很简单,关于我为课程项目创建的网站中的开发人员页面。我正在尝试为每个不同的JButton显示图像和简历。
我在编译时遇到问题,我不断收到NullPointerException错误
在这条线上danPic = new ImageIcon(getClass().getResource("pics/danSkaggs.jpg"));
我假设它为空,因为它无法根据我给它的目录找到图像。但是我不明白我可以做些什么,看不到目录的编写有任何问题。目录为pics / filename.jpg,文件夹与Java代码位于同一软件包中。
这是完整的源代码。
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Developers extends JApplet{
private JButton danButton = new JButton("Dan Skaggs");
private JButton brandonButton = new JButton("Brandon Shaw");
private JButton jamesButton = new JButton("James Simpson");
private JLabel bioLabel = new JLabel("Please click one of the buttons on the left.");
JPanel centerPanel = new JPanel(new GridLayout(1, 2));
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel westPanel = new JPanel(new GridLayout(1, 3));
private ImageIcon danPic;
private ImageIcon brandonPic;
private ImageIcon jamesPic;
private JLabel dLabel;
private JLabel bLabel;
private JLabel sLabel;
//This array carries the Bios of the group project members
String[] bio = new String[]{"Insert Bio",
"Insert Bio",
"Insert Bio"};
public Developers(){
mainPanel.add(westPanel, BorderLayout.WEST);
westPanel.add(danButton);
westPanel.add(brandonButton);
westPanel.add(jamesButton);
centerPanel.add(bioLabel);
mainPanel.add(centerPanel, BorderLayout.CENTER);
danButton.addActionListener(new Handler());
brandonButton.addActionListener(new Handler());
jamesButton.addActionListener(new Handler());
danPic = new ImageIcon(getClass().getResource("pics/danSkaggs.jpg"));
brandonPic = new ImageIcon(getClass().getResource("pics/brandonShaw.jpg"));
jamesPic = new ImageIcon(getClass().getResource("pics/jamesSimpson.jpg"));
dLabel = new JLabel (danPic);
bLabel = new JLabel (brandonPic);
sLabel = new JLabel (jamesPic);
centerPanel.add(dLabel);
add(mainPanel);
}
private class Handler implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()== danButton){
bioLabel.setText(bio[0]);
centerPanel.add(dLabel);
}
else if(event.getSource()== brandonButton){
bioLabel.setText(bio[1]);
centerPanel.add(bLabel);
}
else if(event.getSource()== jamesButton){
bioLabel.setText(bio[2]);
centerPanel.add(bLabel);
}
}
}//end Handler class
}//end Developer class
最佳答案
使用ImageIO代替,它将提供您可以捕获并进行相应处理的exception
。
要么
danPic = new ImageIcon(getClass().getResource("pics/danSkaggs.jpg"));
您缺少
/
,因为pics是程序包名称,必须使用/
来使url
其他明智的pics会嵌入到父目录名称中,以免出错。danPic = new ImageIcon(getClass().getResource("/pics/danSkaggs.jpg"));
Exception
在第一个上,因为它首先执行,也更改了其他两个获取映像的语句。我刚刚测试过它工作正常。