关于Java URL 获取图片路径问题, 具体路径怎么设置, 下小白求指教,源代码如下
packagegraphics.test;importjava.awt.Canvas;importjava.awt.Graphics;importjava.awt.Gra...
package graphics.test;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class DrawImage extends JFrame
{
Image img;
public DrawImage()
{
URL u = DrawImage.class.getResource("img.jpg"); //获取图片资源路径
img = Toolkit.getDefaultToolkit().getImage(u); //获取图片资源
this.setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(new CanvasPanel());
this.setTitle("绘制图片");
}
class CanvasPanel extends Canvas
{
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(img, 0, 0, this);
}
}
public static void main(String[] args)
{
new DrawImage().setVisible(true);
}
} 展开
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class DrawImage extends JFrame
{
Image img;
public DrawImage()
{
URL u = DrawImage.class.getResource("img.jpg"); //获取图片资源路径
img = Toolkit.getDefaultToolkit().getImage(u); //获取图片资源
this.setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(new CanvasPanel());
this.setTitle("绘制图片");
}
class CanvasPanel extends Canvas
{
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(img, 0, 0, this);
}
}
public static void main(String[] args)
{
new DrawImage().setVisible(true);
}
} 展开
若以下回答无法解决问题,邀请你更新回答
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询