1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| public class JAnimationPanel extends JPanel implements ActionListener {
private Timer timer;
private int nombreDeFois;
private int compteur;
private int dx;
private int dy;
private volatile int x;
private volatile int y;
public JAnimationPanel() {
super(true);
timer = new Timer(33, this); // un timer qui appelle une action toutes les 33 ms
timer.setRepeats(true);
setBackground(Color.WHITE);
}
public void start(int x, int y, int dx, int dy, int nombreDeFois) {
timer.stop();
this.x=x;
this.y=y;
this.dx=dx;
this.dy=dy;
this.compteur=0;
this.nombreDeFois=nombreDeFois;
repaint();
if ( nombreDeFois>0 ) {
timer.start();
}
}
public void restart() {
timer.restart();
}
public void stop() {
timer.stop();
}
@Override
public void actionPerformed(ActionEvent e) {
// ici le code qui est éxécuté toutes les 33 ms
x+=dx;
y+=dy;
compteur++;
repaint(); // pour redessiner
if ( compteur>=nombreDeFois ) {
stop();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(x, y, 20, 20);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
frame.getContentPane().add(panel);
final JAnimationPanel timerpanel = new JAnimationPanel();
panel.add( timerpanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
panel.add( buttonPanel, BorderLayout.SOUTH);
JButton button1 = new JButton("Lancer");
buttonPanel.add( button1 );
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timerpanel.start(0, 0, 1, 0, 100);
}
});
JButton button2 = new JButton("Stop");
buttonPanel.add( button2 );
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timerpanel.stop();
}
});
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
Partager