如何按顺序移动图像?

时间:2014-03-25 05:24:52

标签: java swing timer imageicon

我正在尝试制作Java桌面应用程序,我想让自动图像洗牌我能够做到这一点,但问题是它不是洗牌我给的所有图像我想要洗牌所有图像 我怎么能实现这个

以下是我找到的一些代码here

/**
 * @see https://stackoverflow.com/a/22423511/230513
 * @see https://stackoverflow.com/a/12228640/230513
 */
public class ImageShuffle extends JPanel {

   private List<Icon> list = new ArrayList<Icon>();

   private JLabel label = new JLabel();
   private Timer timer = new Timer(1000, new ActionListener() {

      @Override
       public void actionPerformed(ActionEvent e) {
        update();
       }
   });

   public ImageShuffle() {
       this.setLayout(new GridLayout(1, 0));

      list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\e.jpg"));
    list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\d.jpg"));
    list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\yellow.png"));
      list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\f.jpg"));
         //   list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\yellow.jpg"));
       //label.setIcon(UIManager.getIcon("OptionPane.informationIcon"));

       timer.start();
   }

   private void update() {

    Random r=new Random();
    int i1=(r.nextInt(3) +1);

    label.setIcon(list.get(i1));
}

private void display() {
    JFrame f = new JFrame("ImageShuffle");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(this);
    f.add(label);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

           @Override
          public void run() {
              new ImageShuffle().display();
           }
       });
   }
 }

提前致谢

1 个答案:

答案 0 :(得分:2)

首先创建一个混洗列表...

private List<Icon> list = new ArrayList<Icon>();
private List<Icon> shuffled;

//...

list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\e.jpg"));
list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\d.jpg"));
list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\yellow.png"));
list.add(new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\f.jpg"));

shuffled = new ArrayList<Icon>();
update();

每次你的计时器滴答并调用actionPerformed时,弹出shuffled列表的第一个元素,直到没有剩下......

 if (shuffled.isEmpty()) {
    shuffled.addAll(list);
    // Prevent the current image from been selected next...
    shuffled.remove(label.getIcon());
    Collections.shuffle(shuffled);
 }

 Icon icon = shuffled.remove(0);
 label.setIcon(icon);

这将消除允许连续多次显示图像的可能性。无论如何,你的随机值计算应该更像int i1 = (r.nextInt(list.size())); ...

备注:

ImageShuffle不需要从JPanel延伸,您不需要添加任何内容。这意味着你可以摆脱this.setLayout(new GridLayout(1, 0));f.add(this);,程序应该仍然运行