java中一个图片在另外中一个背景图片中能动的代码

2022-03-10 社会 66阅读

写出来发现写的有点多不明白可以追问我真的不想写注释资源我用的是网上的url没有图片显示你可以自己更换图片url网上随便找一个就行就一个类编译后直接可以运行

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JPanel
{

private static final long serialVersionUID = 1L;
private BufferedImage back, front, buffer;
private Graphics2D g2d;
private JFrame window;
private int x,y;
public Test() throws IOException
{
x=0;y=100;
buffer=new BufferedImage(600,500,BufferedImage.TYPE_INT_ARGB);
g2d=buffer.createGraphics();
window=createGui();
front=getImage("http://cdn.patch.com/users/112920/2015/04/T800x600/201504552ae941c06ae.jpg");
back=getImage("http://www.destination-languedoc.co.uk/docs/1665-9-pic-st-loup-herault-le-languedoc.gif");
window.getContentPane().add(this);
window.pack();
window.setVisible(true);
process();
}
public void process()
{
int speed=2;
while (true)
{
g2d.drawImage(back,0,0,600,500,this);
g2d.drawImage(front, x, y, 300,300,this);
x+=speed;
if (x+300>600)
speed*=-1;
else if (x speed*=-1;
this.repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public BufferedImage getImage(String path) throws IOException
{
BufferedImage buffer=null;
URL url=new URL(path);
URLConnection con=url.openConnection();
buffer=ImageIO.read(con.getInputStream());
return(buffer);
}
public JFrame createGui()
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout());
frame.getContentPane().setPreferredSize(new Dimension(600,500));
return(frame);
}
public static void main(String[] args)
{
try {
new Test();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
g.drawImage(buffer, 0, 0, 600,500,this);
}
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com