图片路径都是正确的,我不知道为什么会出现这个错误。有人知道吗?
代码用于将背景图像放在框架中并在该图像上添加按钮
错误是
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:99)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:113)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
代码
运行代码时出现错误:
public class BackgroundImg extends JPanel {
private Image img;
public BackgroundImg (String img)
{
this(new ImageIcon(img).getImage());
}
public BackgroundImg (Image img)
{
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
//setLayout(null);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
}
public class ApplicationFrame {
public static void main(String[] args) throws ImageAccessException {
BackgroundImg panel = new BackgroundImg(Toolkit.getDefaultToolkit().createImage(ApplicationFrame.class.getResource("C:\\test.png")));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.getContentPane().add(panel);
ApplicationContents.addContentsToPane(panel);
frame.setVisible(true);
// frame.setVisible(true);
}
}
}
public class ApplicationContents {
public static void addContentsToPane(Container pane)
{
//pane.setLayout(null);
pane.setLayout(new FlowLayout());
JButton b1 = new JButton("Test");
pane.add(b1);
//Insets insets = pane.getInsets();
//Dimension size = new Dimension(120,32);
// b1.setBounds(0 + insets.left, 0 + insets.top,
// size.width, size.height);
b1.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JOptionPane.showMessageDialog(null, "Test" , "Test", JOptionPane.ERROR_MESSAGE);
}
}
);
}
}