0
嗨我正在嘗試創建一個Java桌面應用程序,我可以每5秒自動移動一次圖像。我能夠做到這一點。問題是我想使用自己的圖像,並且我想將所有圖像放在單個Jlabel上。我沒有下面的代碼如何自動更改Jlabel
我怎麼能得到這個?
private static class ImagePanel extends JPanel {
URL[] urls;
ImageIcon[] image;
BufferedImage[] images;
Random rand = new Random();
JLabel imagelabel;
public ImagePanel() {
urls = new URL[4];
try {
urls[0] = new URL("http://i.stack.imgur.com/NCsHu.png");
urls[1] = new URL("http://i.stack.imgur.com/UvHN4.png");
urls[2] = new URL("http://i.stack.imgur.com/s89ON.png");
urls[3] = new URL("http://i.stack.imgur.com/QEK2o.png");
images = new BufferedImage[5];
images[0] = ImageIO.read(urls[0]);
images[1] = ImageIO.read(urls[1]);
images[2] = ImageIO.read(urls[2]);
images[3] = ImageIO.read(urls[3]);
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
setBackground(Color.BLACK);
Timer timer = new Timer(5000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
private int random() {
int index = rand.nextInt(4);
return index;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage img = images[random()];
g.drawImage(img, 0, 0, 400, 400, 0, 0,
img.getWidth(), img.getHeight(), this);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
在此先感謝