使用Java创建重复的幻灯片放映

时间:2019-07-15 12:26:57

标签: java

我正在尝试创建图像幻灯片,我已将当前代码移至右侧,然后移回左侧,但是我希望图像从左侧移至右侧,然后从向左走,然后向右走,然后从左边出来。 请帮助

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MImage extends JPanel implements ActionListener {

    Timer t = new Timer(10, this);
    int x = 2, y = 2, velX = 2, velY = 2;
    Image image;
    int num = 0;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        ImageIcon i = new ImageIcon("image/cartoon.jpg");
        image = i.getImage();
        g.drawImage(image, x, velY, null);
        t.setRepeats(true);
        t.start();

    }

    public void actionPerformed(ActionEvent e) {



        if (x < 0 || x >= 1500) {
            velX = -velX;
        }

        if (y < 0 || y >= 3000) {
            velY = -velY;
        }



        x += velX;
        y += velY;
        repaint(x);
    }

}

SMimage类

import javax.swing.JFrame;

public class SMImage {

    public static void main(String[] args) {

        MImage im = new MImage();
        JFrame f = new JFrame();

        f.add(im);
        f.setVisible(true);
        f.setSize(600, 400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setTitle("Moving image");
    }

}

它不断向右移动,然后向左移动

1 个答案:

答案 0 :(得分:0)

完成所需操作的最简单方法是将图像绘制在图像居中版本的左侧和右侧。

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, x - image.getWidth(this), velY, this);
    g.drawImage(image, x, velY, this);
    g.drawImage(image, x + image.getWidth(this), velY, this);

}