java/swing

java swing 예제- 중력 구현

aphyrince 2022. 1. 8. 02:22
반응형

 

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();
	}
}
반응형