java/swing

Java swing 예제 - 점프 구현

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

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 Jump extends JFrame{
	
	private int height = 570;
	private int velocity =0;
	private int gravity = 1;
	
	public Jump() {
		this.setTitle("Jump High");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setSize(300,600);
		this.setVisible(true);
		
		JButton button = new JButton("점프");
		button.setBackground(Color.blue);
		button.addMouseListener(new MouseListener() {
			@Override
			public void mouseClicked(MouseEvent e) {
				velocity+=20;
			}@Override
			public void mousePressed(MouseEvent e) {}
			@Override
			public void mouseReleased(MouseEvent e) {}
			@Override
			public void mouseEntered(MouseEvent e) {}
			@Override
			public void mouseExited(MouseEvent e) {}});
		button.setBounds(0,270,60,30);
		add(button);
		
		
		while(true) {
			try {Thread.sleep(18);}catch(InterruptedException e) {}
			if(height>570 && velocity<0) {
				height = 570;
				velocity=0;
			}
			else {
				height-=velocity;
				velocity-=gravity;
			}
			repaint();
		}
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		g.fillRect(100, height, 30,30);
	}
	
	public static void main(String[] args) {
		new Jump();
	}
}
반응형