通过每次打开图片位置不一样实现动态爱心降落。
程序效果如图所示:
代码 :
import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ax { private Jframe jframe; private JPanel axJPanel; private final int TABLE_WIDTH = 410; private final int TABLE_HEIGHT = 390; private int Image_x = 0; private int Image_y = 0; private int speed = 50; private Timer timer; private BufferedImage image; private class MyCanvas extends JPanel { @Override public void paint(Graphics g) { g.drawImage(image, Image_x, Image_y, null); g.drawImage(image, 0,0, null); } } MyCanvas myDraw=new MyCanvas(); public void init(){ try { image= ImageIO.read(new File("C:\Users\ywz\IdeaProjects\JingJie\.idea\image\ax.jpg")); } catch (IOException e) { e.printStackTrace(); } myDraw.repaint(); ActionListener actionListener=new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myDraw.repaint(); Image_y+=speed; if (Image_y>TABLE_HEIGHT){ Image_y=0; Image_x+=speed; } } }; timer=new Timer(100,actionListener); timer.start(); myDraw.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT)); axJPanel=new JPanel(); jframe=new Jframe(); axJPanel.add(myDraw); jframe.add(axJPanel); jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jframe.setSize(TABLE_WIDTH,TABLE_HEIGHT); jframe.setVisible(true); } public static void main(String[] args) { new ax().init(); } }注意:init方法中的image后的new File括号后面是爱心图片的储存位置,记得修改!!!
以下是爱心图片
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)