반응형


package 중력구현;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Gravitys extends JFrame{
private final int MAX_HEIGHT = 670;
private int height = MAX_HEIGHT;
private int velocity = 0;
private int accel = 1;
private int gravity = 1;
private boolean isClicked = false;
public Gravitys() {
this.setTitle("중력구현");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(300,700);
this.setVisible(true);
JButton button = new JButton("가속");
button.setBounds(0,250,70,50);
button.setBackground(Color.gray);
button.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
isClicked = true;
}
@Override
public void mouseReleased(MouseEvent e) {
isClicked = false;
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
});
add(button);
while(true) {
try{Thread.sleep(18);}catch(InterruptedException e) {}
if(isClicked)
startAccel();
else
stopAccel();
repaint();
}
}
public void startAccel() {
if(height<=30) {
height=30;
velocity=0;
}
else if(height>670) {
height = 670;
velocity=0;
}
else {
height-=velocity;
velocity+=accel;
}
}
public void stopAccel() {
if(height>670) {
height =670;
velocity=0;
}
else if( height<30) {
height = 30;
velocity=0;
velocity-=gravity;
}
else {
height-=velocity;
velocity-=gravity;
}
}
public void paint(Graphics g) {
super.paint(g);
g.fillRect(120, height, 30, 30);
}
public static void main(String[] args) {
new Gravitys();
}
}반응형
'java > swing' 카테고리의 다른 글
| Java swing 예제 - 점프 구현 (0) | 2022.01.08 |
|---|---|
| java swing 예제 - Up Down 게임 (0) | 2022.01.08 |
| java swing 예제 - 키보드로 사각형 움직이기 (0) | 2022.01.08 |
| 명품 JAVA - Open Challenge 12 아바타와 괴물 게임 만들기 - swing,thread (0) | 2022.01.08 |
| 명품 JAVA - Open Challenge 10 버튼 클릭으로 좌우로 이미지 넘기기 - swing (0) | 2022.01.08 |