I am trying to randomly move multiple images in jframe.They should move randomly all over the window . I can do it only for a single images.But when i am trying to do that multiple images , i can't.Here is the code for moving one image randomly. Please give me some idea what i should do to work the code for multiple images
package javaapplication13;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
class animate extends JPanel implements Runnable
{
Image img;
int x=100,y=100,d=10;
double angle=0;
int width,height;
int DELAY=10;
animate(int a,int b,String str)
{
width=a;height=b;
ImageIcon ii = new ImageIcon(str);
img=ii.getImage();
new Thread(this).start();
}
@Override
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
int cnt=0;
while(true)
{
if (cnt>30)
{
cnt=0;
angle=(Math.random()*360)%360;
}
cnt++;
x+=Math.cos(angle)*d;
y+=Math.sin(angle)*d;
if (x>width)
{
x=width;
angle=(Math.random()*360)%360;
}
else if (y>height)
{
y=height;
angle=(Math.random()*360)%360;
}
if (x<0)
{
x=0;
angle=(Math.random()*360)%360;
}
if (y<0)
{
y=0;
angle=(Math.random()*360)%360;
}
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep < 0) {
sleep = 2;
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e.getMessage());
}
beforeTime = System.currentTimeMillis();
}
}
public void paint(Graphics g)
{
super.paintComponent(g);
g.drawImage(img,x,y,null);
}
}
public class DrawImageOnJFrame extends JFrame
{
public DrawImageOnJFrame()
{
//set JFrame title
super("Draw Image On JFrame");
//Get image. You must change image location follow to image location in your computer.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700,700);
setResizable(false);
setVisible(true);
add(new animate(700,700,"fish.png"));
add(new animate(700,700,"cat.jpg"));
}
public static void main(String[]args)
{
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(animation.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
}
DrawImageOnJFrame diojf=new DrawImageOnJFrame();
}
});
}
}
Aucun commentaire:
Enregistrer un commentaire