我使用了以下代码:
g.drawImage(Toolkit.getDefaultToolkit().createImage(new
URL(".\\mouseicon1.bmp")), MouseX,MouseY,null);
并且图像文件(mouseicon1.bmp
)位于同一个包中,但它会抛出此异常:
java.net.MalformedURLException: no protocol: .\mouseicon1.bmp
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at (insertnameofpackagehere).launch$Board.paint(launch.java:48)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
答案 0 :(得分:3)
正如错误所述,URL需要一个协议。对于本地文件,您可以在使用URL时使用file://作为协议。或者您可以将文件转换为URL:
new File(path).toURI().toURL();
答案 1 :(得分:1)
如果您只是在本地计算机上查找文件,则应该使用以下方法
ToolKit.getDefaultToolkit().createImage(String filename);
但是如果你真的想使用URL,那么我相信这会完成同样的事情
Toolkit.getDefaultToolkit().createImage(new URL("file://./test.bmp"))