【问题标题】:I want to iterate through an arraylist of Images我想遍历图像的数组列表
【发布时间】:2019-12-04 14:18:24
【问题描述】:

我有一个图像数组列表,我试图让每张图像反复滑过屏幕..

public class GraphicsT extends JPanel implements ActionListener {

    Timer timer = new Timer(1, this);
    Image image;
    Image image2;
    int x1;
    int x2;
    int y1;
    int y2;
    int num;

    List<String> imageList1 = new ArrayList<String>();

    GraphicsT() {
        imageList1.add("image/java.jpeg");
        imageList1.add("image/slide.jpg");
        imageList1.add("image/giphy.gif");
        x1 = 100;
        y1 = 100;
        x2 = 200;
        y2 = 200;
        num = 0;
    }

    public void paint(Graphics g) {

        ImageIcon i2 = new ImageIcon("image/street.jpg");
        image2 = i2.getImage();
        g.drawImage(image2, 0, 0, null);

        for (int i = 1; i < imageList1.size(); i++) {

            ImageIcon im = new ImageIcon(imageList1.get(i));
            image = im.getImage();
            g.drawImage(image, x1, y1, x2, y2, 100, 120, 120, 240, null);

            System.out.println(imageList1.get(i));

        }
        timer.start();

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        num++;
        if (num % 100 == 0) {
            x1 = x1 + 10;
            x2 = x2 + 10;
        }

        if (x2 >= 570) {
            // end reached
            x1 = 0;
            x2 = 100;
        }

        repaint();

    }
}


public class GraphicsApp extends JFrame {

    GraphicsT gt = new GraphicsT();

    public GraphicsApp() {
        this.setTitle("Multiple Slide");
        this.setSize(450, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.add(gt);
    }

    public static void main(String[] args) {
        new GraphicsApp();
    }

}

我当前的代码只能选择一个图像,但我想要一种情况,即在第一个图像离开屏幕后,第二个图像可以跟随,然后是第三个,依此类推......

我们将不胜感激。

【问题讨论】:

    标签: java swing arraylist jpanel swingx


    【解决方案1】:

    几个问题:

    1. 您应该覆盖 paintComponent() 而不是 paint(),并调用 super.paintComponent(...) 以确保首先绘制背景。

    2. 一种绘画方法仅用于绘画。您不应该通过 I/O 来读取图像。应该在类的构造函数中读取图像

    3. 您不应该在绘画方法中启动 Timer。 Timer 在构造函数中启动。

    4. 您的基本绘画代码错误。你应该有几个实例变量,a)“currentImage”,b)“imageNumber”。然后在绘画方法中,您只需在 x/y 位置绘制 currentImage 即可。

      在 ActionListener 中,当图像离开屏幕时,您增加“imageNumber”并将图像从 ArrayList 复制到“currentImage”。然后重置 x/y 位置,以便从右侧开始绘制图像。

      当“imageNumber”到达 ArrayList 的末尾时,将其重置为 0。

    【讨论】:

    • 这实际上是我第一次在摇摆上工作,请举个例子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2015-07-29
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多