问题
I am trying to make Java desktop application where i want to make auto image shuffle i am able to do this but problem is that it is not shuffling all image which i gave i want to shuffle all image how can i achieve this
Here is some code I found 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();
}
});
}
}
Thanks in advance
回答1:
Start by creating a shuffled list...
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();
Each time your timer ticks and calls actionPerformed
, pop the first element of the shuffled
list until nothing is left...
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);
This will remove the possibility of an image been allowed to be displayed multiple times in a row. Your random value calculation should have been more like int i1 = (r.nextInt(list.size()));
anyway...
Notes:
ImageShuffle
doesn't need to extend from JPanel
, you not adding anything to it. This means you can get rid of this.setLayout(new GridLayout(1, 0));
and f.add(this);
and the program should still run
来源:https://stackoverflow.com/questions/22626064/how-to-shuffle-image-in-sequence