멀티스레드프로그래밍2 : 풍선게임

  • 클릭하면 풍선이 나타나고 위로 올라가는 풍선게임을 만들어보자.
  • MouseEvent -> y축을 이동
  • sleep : 반응시간
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
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class BaloonThreadEx extends JFrame{
JPanel p;

BaloonThreadEx(){
setTitle("Baloon");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
p.setLayout(null);
p.addMouseListener(new MouseAdapter(){

@Override
public void mousePressed(MouseEvent e) {

BaloonThread t= new BaloonThread(e.getX(), e.getY());
t.start();
}
});
setContentPane(p);

setSize(500,500);
setVisible(true);
}

class BaloonThread extends Thread {
int x,y;
BaloonThread(int x, int y){
this.x=x;
this.y=y;
}

@Override
public void run() {
ImageIcon icon = new ImageIcon("images/balloon.jpg");
JLabel baloon = new JLabel(icon);
baloon.setSize(60,60);
baloon.setLocation(x, y);
p.add(baloon);

while(y>0){
y-=20; //0.2초마다 얼마만큼 위로 올라가는지 숫자가 클수록 빨리 올라가는 느낌 but부자연스러움
try{
Thread.sleep(200); //0.2초마다
}catch(Exception e){
e.toString();
}
baloon.setLocation(x, y);
//p.repaint();
}
p.remove(baloon);
}
}

public static void main(String[] args) {
new BaloonThreadEx();
}
}

Comments