mojo's Blog

명품 JAVA Programming 제 12장 Open Challenge 본문

Java

명품 JAVA Programming 제 12장 Open Challenge

_mojo_ 2021. 8. 4. 01:40

Cliping 기능을 이용하여 재미있는 오락용 프로그램 작성하기

import javax.swing.*; // JFrame
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*; // Container
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Vector;
import java.awt.*;

public class MyFrame extends JFrame{

	private MyPanel panel = new MyPanel();
	private int x=50, y=50;
	private Graphics gp;
	
	MyFrame(){
		setTitle("12장 Open Challenge");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		setContentPane(panel);
		
		addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				int keyCode = e.getKeyCode();
				repaint();
				
				if(keyCode==KeyEvent.VK_UP) {
					if(y-10>=0) {
						y-=10;
					}
				}
				else if(keyCode==KeyEvent.VK_DOWN) {
					if(y+10<=getHeight()) {
						y+=10;
					}
				}
				else if(keyCode==KeyEvent.VK_LEFT) {
					if(x-10>=0) {
						x-=10;
					}
				}
				else if(keyCode==KeyEvent.VK_RIGHT) {
					if(x+10<=getWidth()) {
						x+=10;
					}
				}
				
				gp.setClip(x,y,50,50);
			}
		});
		
		setSize(400, 400); 
		setVisible(true); 
		
		setFocusable(true);
		requestFocus();
	}
	
	class MyPanel extends JPanel{
		private ImageIcon icon = new ImageIcon("C:\\\\Temp/Kitty.png");
		private Image img = icon.getImage();
		
		public void paintComponent(Graphics g) {
			gp = g;
			super.paintComponent(g);
			g.setClip(x, y, 50, 50);			
			g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new MyFrame();
	}

}

 

'Java' 카테고리의 다른 글

Multitasking  (0) 2021.08.08
명품 JAVA Programming 제 12장 실습문제 (3~4 제외)  (0) 2021.08.04
마우스를 이용하여 선 그리기  (0) 2021.08.04
이미지 그리기 / Clipping  (0) 2021.08.04
도형 그리기와 칠하기  (0) 2021.08.04
Comments