JAVA 프로그래밍

문제

마우스를 클릭한 위치에서 선물이 아래로 떨어지는 문제입니다 실행순서를 클릭하세요 
           
 

프로그램 코드

E001	// 이벤트 대기중
E002	// 패널 영역에서 마우스 클릭하기
E003	// 0.5초마다 타이머 활성화

	import javax.swing.*;
		
	public class PresentDropGUIMain
	{
1		public static void main(String[] args)
		{
			final String background = "C:\\Users\\user\\Downloads\\JAVA-main\\Chapter13\\image\\background.jpg";

			JFrame frame = new JFrame ( "선물 배달" );
2			frame.getContentPane().add( new PresentDropPanel( background ) );
			frame.pack();
			frame.setVisible(true);
			frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
3		}
	}

	import java.awt.*;
	import java.awt.event.*;
	import javax.swing.*;
	import java.util.ArrayList;

	public class PresentDropPanel extends JPanel {
		protected ArrayList<Present> presents;
		protected Image background;
D1b		public PresentDropPanel( String background ) {
			this.presents = new ArrayList<Present>();
			this.background = new ImageIcon( background ).getImage();
			setPreferredSize( new Dimension( 400, 400 ) );
			setFocusable( true );
			requestFocus();
			
			this.addMouseListener( new MouseAdapter() {
				@Override
L1b				public void mouseClicked( MouseEvent event ) {
L11					presents.add( new Present( event.getX(), event.getY() ) );
L1e				}
			} );
			Timer timer = new Timer( 50, new ActionListener() {
				@Override
L2b				public void actionPerformed( ActionEvent event ) {
					for( Present present : presents )
L21						present.drop();
L22					repaint();
L2e				}
			} );
			timer.start();
D1e		}
		
		@Override
D2b		public void paint( Graphics g ) {
			super.paintComponent( g );
			g.drawImage( background, 0, 0, null );
			for( Present present : presents )
D21				present.paint(g);
D2e		}
	}

	import java.awt.*;
			
	public class Present
	{
		int x, y;
P1b		public Present( int x, int y ) {
			this.x = x;
			this.y = y;
P1e		}
P2b		public void drop() {
			this.y += 10;
P2e		}
P3b		public void paint( Graphics g ) {
			g.setColor( Color.red );
			g.fillRect( x,    y,    10, 10 );
			g.fillRect( x+20, y,    10, 10 );
			g.fillRect( x,    y+20, 10, 10 );
			g.fillRect( x+20, y+20, 10, 10 );
			g.setColor( new Color( 0, 100, 0 ) );
			g.fillRect( x+10, y,    10, 30 );
			g.fillRect( x,    y+10, 30, 10 );
P3e		}
	}








 
실행 순서