-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path73_2dAnimation
More file actions
78 lines (66 loc) · 2.02 KB
/
73_2dAnimation
File metadata and controls
78 lines (66 loc) · 2.02 KB
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
<Main.java>
public class Main {
public static void main(String[] args){
new MyFram();
}
}
<MyFram.java>
import javax.swing.*;
import java.awt.*;
public class MyFram extends JFrame {
MyPanel panel;
MyFram(){
panel = new MyPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(panel);
this.pack();
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
<MyPanel.java>
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyPanel extends JPanel implements ActionListener {
final int PANEL_WIDTH = 500;
final int PANEL_HEIGHT = 500;
Image search;
Image backgroundImage;
Timer timer;
int xVelocity = 2; //if 1 move in top left to bottom right, if 2 move like >
int yVelocity = 1;
int x = 0;
int y = 0;
MyPanel(){
this.setPreferredSize((new Dimension(PANEL_WIDTH,PANEL_HEIGHT)));
this.setBackground(Color.black);//Background image will replace
search = new ImageIcon("smile.png").getImage();
backgroundImage = new ImageIcon("pizza.png").getImage();
timer = new Timer(100,this);//delay, listener
timer.start();
}
public void paint(Graphics g){
super.paint(g);//paint background
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(backgroundImage,0,0,null);
g2D.drawImage(search,x,y,null);//img, x, y, null
}
@Override
public void actionPerformed(ActionEvent e) {
//Move horizontally back & forth
if(x>=PANEL_WIDTH - search.getWidth(null )|| x<0){
xVelocity = xVelocity * -1;
}
x = x + xVelocity;
repaint();//or else resize window to repaint
//To move vertically
if(y>=PANEL_WIDTH - search.getWidth(null) || y<0){
yVelocity = yVelocity * -1;
}
y = y + yVelocity;
}
//Have both vertical & horizontal --> diagonal
}