这个小程序是一个简单的关于我正在为一个类项目创建的网站中的开发人员页面。我正在尝试为每个不同的 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