Java爱心降落(动态爱心降落)

通过每次打开图片位置不一样实现动态爱心降落。

程序效果如图所示:

 

 

代码 :

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括号后面是爱心图片的储存位置,记得修改!!!

以下是爱心图片

 

 

 

你可能感兴趣的:(java)