写了个打地鼠小程序,运行报空指针异常。怎么也找不出哪里出错,求大神帮帮找一下,搞了一晚上了。
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Shrewmouse extends JFrame implements Runnable
{
private static final long serialVersionUID = 8752899717443325480L;
private JLabel[] mouses;
private ImageIcon imgMouse;
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Shrewmouse frame = new Shrewmouse();
frame.setVisible(true);
new Thread(frame).start();
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public Shrewmouse()
{
super();
setResizable(false);
getContentPane().setLayout(null);
setTitle("打地鼠游戏");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon(getClass().getResource("C:/background.jpg"));
imgMouse = new ImageIcon(getClass().getResource("C:/mouse.png"));
mouses = new JLabel[6];
for (int i = 0; i < 6; i++)
{
mouses[i] = new JLabel();
mouses[i].setSize(imgMouse.getIconWidth(), imgMouse.getIconHeight());
mouses[i].addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
Object source = e.getSource();
if (source instanceof JLabel)
{
JLabel mouse = (JLabel) source;
mouse.setIcon(null);
}
}
});
getContentPane().add(mouses[i]);
}
mouses[0].setLocation(253, 300);
mouses[1].setLocation(333, 250);
mouses[2].setLocation(388, 296);
mouses[3].setLocation(362, 364);
mouses[4].setLocation(189, 353);
mouses[5].setLocation(240, 409);
final JLabel backLabel = new JLabel();
backLabel.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
setBounds(100, 100, img.getIconWidth(), img.getIconHeight() + 30);
backLabel.setIcon(img);
getContentPane().add(backLabel);
}
public void run()
{
while (true)
{
try
{
Thread.sleep(1000);
int index = (int) (Math.random() * 6);
if (mouses[index].getIcon() == null)
mouses[index].setIcon(imgMouse);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
|