Is there a way in Java swing to give a sprite the effect like it is live? Like moving randomly it around its center and having a fluctuating effect?
I tried something like the following (but the result is horrible):
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main extends JFrame {
private static final int W = 800;
private static final int H = 400;
private int last = -1;
public Main() {
super("JFrame");
this.add(new ImagePanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
setSize(W, H);
this.setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Main();
}
});
}
class ImagePanel extends JPanel {
Timer movementTimer;
int x, y;
public ImagePanel() {
x = 58;
y = 58;
movementTimer = new Timer(12, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveImage();
repaint();
}
});
movementTimer.start();
}
public void moveImage() {
if (last < 0) {
last = random();
x += last;
y += last;
} else {
x -= last;
y -= last;
last = -1;
}
if (x > W) {
x = 0;
}
if (y > H) {
y = 0;
}
}
private int random() {
Random r = new Random();
int Low = 2;
int High = 14;
int Result = r.nextInt(High - Low) + Low;
return Result;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
long start = System.nanoTime();
g.setColor(Color.RED);
g.fillRect(0, 0, W, H);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 50);
}
}
}
The result is not smooth at all, do you have any suggestion ?