마우스를 클릭한 위치에서 선물이 아래로 떨어지는 문제입니다 이를 해결하는 다음 프로그램을 해석하세요
선물 클래스
클릭 위치에 선물 생성
선물 낙하
선물 그리기
선물 배달 패널 클래스
마우스 클릭시 선물 생성
선물은 주기적으로 조금씩 낙하
선물 및 배경의 화면 업데이트
|
빨간 정사각형 4개
초록 직사각형 2개 |
E001 // 이벤트 대기중
E002 // 패널 영역에서 마우스 클릭하기
E003 // 0.5초마다 타이머 활성화
// 파일명 : ./Chapter13/PresentDropGUIMain.java
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 }
}
// 파일명 : ./Chapter13/PresentDropPanel.java
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 }
}
// 파일명 : ./Chapter13/Present.java
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 }
}
※ 실행순서 및 메모리상태는 A키(이전) 및 D키(다음)를 눌러도 확인할 수 있습니다