대학교 수업/Java 프로그래밍

[Java] 명품 자바 프로그래밍 13장 실습문제 (1~8)

Jongung 2022. 12. 5. 18:56

1번

import javax.swing.*;
import java.util.Scanner;

public class Chapter13 extends JFrame {
    class MyThread implements Runnable {
        public void run() {
            System.out.println("스레드 실행 시작");
            for(int i=1; i<=10; i++)
                System.out.print(i + " ");
            System.out.println();
            System.out.println("스레드 종료");
        }
    }
    Chapter13(){
        Scanner scanner = new Scanner(System.in);
        System.out.print("아무 키나 입력>> ");
        scanner.nextLine();
        scanner.close();
        Thread th = new Thread(new MyThread());
        th.start();
    }
    static public void main(String [] args) {
        new Chapter13();
    }
}

 

2번

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

public class Chapter13 extends JFrame{
    class MyPanel extends JPanel{
        public void paintComponent(Graphics g) {
            g.setColor(Color.MAGENTA);
            int x = (int)(Math.random()*180);
            int y = (int)(Math.random()*180);
            g.drawOval(x, y, 50, 50);
        }
    }

    class MyThread extends Thread{
        MyPanel panel;
        public MyThread(MyPanel p) {
            panel = p;
        }
        public void run() {
            for(;;){
                try {
                    sleep(400);
                    panel.repaint();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    Chapter13() {
        MyPanel panel = new MyPanel();
        MyThread th = new MyThread(panel);
        setTitle("원을 0.5초 간격으로 이동하는 frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setContentPane(panel);
        panel.setLayout(null);
        panel.setOpaque(true);
        panel.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                th.start();
            }
        });
        setVisible(true);
        setSize(300,300);
    }
    public static void main(String[] args) {
        new Chapter13();
    }
}

 

3번

import javax.swing.*;
import java.awt.*;
import java.util.Calendar;

public class Chapter13 extends JFrame {
    Chapter13() {
        setTitle("디지몬 시계 만들기");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container c = getContentPane();
        c.add(new MyLabel());
        setSize(400,300);
        setVisible(true);
    }

    class MyLabel extends JLabel implements Runnable {
        Thread timerThread;
        MyLabel() {
            setText(makeClockText());
            setFont(new Font("Gothic", Font.PLAIN, 70));
            setHorizontalAlignment(JLabel.CENTER);
            timerThread = new Thread(MyLabel.this);
            timerThread.start();
        }

        String makeClockText() {
            Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int min = c.get(Calendar.MINUTE);
            int second = c.get(Calendar.SECOND);

            String clockText = Integer.toString(hour);
            clockText = clockText.concat(":");
            clockText = clockText.concat(Integer.toString(min));
            clockText = clockText.concat(":");
            clockText = clockText.concat(Integer.toString(second));
            return clockText;
        }

        public void run() {
            while(true) {
                try {
                    Thread.sleep(1000);
                }
                catch(Exception e){
                    e.printStackTrace();
                }
                finally {
                    setText(makeClockText());
                }
            }
        }
    }

    public static void main(String [] args) {
        new Chapter13();
    }
}

 

4-1번

import javax.swing.*;

public class Chapter13 extends JFrame {
    Chapter13() {
        setTitle("진동하는 프레임 만들기");
        setDefaultCloseOperation(3);
        MyThread th = new MyThread(this);
        th.start();
        setSize(500,500);
        setVisible(true);
    }

    class MyThread extends Thread{
        JFrame frame;
        int x = 300;
        public MyThread(JFrame jf){
            this.frame = jf;
        }

        public void run() {
            while(true) {
                if (x == 300) x += 3;
                else x -= 3;
                frame.setLocation(x,500);
                try{
                    Thread.sleep(100);
                }catch (InterruptedException ex){
                    return;
                }
            }
        }
    }

    public static void main(String[] args) {
        new Chapter13();
    }

}

4-2번

import javax.swing.*;
import java.awt.*;

public class Chapter13 extends JFrame {
    Chapter13() {
        setTitle("진동하는 프레임 만들기");
        setDefaultCloseOperation(3);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        MyThread th = new MyThread();
        c.add(th);
        setSize(500,500);
        setVisible(true);
    }

    class MyThread extends JLabel implements Runnable{
        int x = 250;
        public MyThread(){
            setText("진동 레이블");
            setLocation(250, 200);
            setFont(new Font("Arial", Font.PLAIN, 30));
            Thread th = new Thread(this);
            th.start();
        }

        public void run() {
            while(true) {
                if (x == 250) x += 3;
                else x -= 3;
                this.setLocation(x,200);
                try{
                    Thread.sleep(100);
                }catch (InterruptedException ex){
                    return;
                }
            }
        }
    }

    public static void main(String[] args) {
        new Chapter13();
    }

}

 

5번

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

public class Chapter13 extends JFrame{
    Chapter13() {
        setTitle("사격 게임");
        setDefaultCloseOperation(3);

        GamePanel p = new GamePanel();
        setContentPane(p);
        setSize(300,300);
        setResizable(false);
        setVisible(true);
        p.startGame();
    }

    public static void main(String [] args) {
        new Chapter13();
    }
}
class GamePanel extends JPanel {
    TargetThread targetThread = null;
    JLabel baseLabel = new JLabel();
    JLabel bulletLabel = new JLabel();
    JLabel targetLabel;

    public GamePanel() {
        setLayout(null);

        baseLabel.setSize(40,40);
        baseLabel.setOpaque(true);
        baseLabel.setBackground(Color.BLACK);

        ImageIcon img = new ImageIcon("src/chicken.jpg");
        targetLabel = new JLabel(img);
        targetLabel.setSize(img.getIconWidth(),img.getIconWidth());

        bulletLabel.setSize(10,10);
        bulletLabel.setOpaque(true);
        bulletLabel.setBackground(Color.RED);
        add(baseLabel);
        add(targetLabel);
        add(bulletLabel);

        this.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                baseLabel.setFocusable(true);
                baseLabel.requestFocus();
            }
        });
    }

    public void startGame() {
        baseLabel.setLocation(this.getWidth() / 2 - 20, this.getHeight() - 40);
        bulletLabel.setLocation(this.getWidth() / 2 - 5, this.getHeight() - 50);
        targetLabel.setLocation(0, 0);

        targetThread = new TargetThread(targetLabel);
        targetThread.start();

        baseLabel.setFocusable(true);
        baseLabel.requestFocus();
        baseLabel.addKeyListener(new KeyAdapter() {
            BulletThread  bulletThread = null;

            public void keyPressed(KeyEvent e) {
                if(e.getKeyChar() == '\n') {
                    if(bulletThread==null || !bulletThread.isAlive()) {
                        bulletThread = new BulletThread(bulletLabel, targetLabel, targetThread);
                        bulletThread.start();
                    }
                }
            }
        });
    }

    class TargetThread extends Thread {
        private JComponent target;
        public TargetThread(JComponent target) {
            this.target = target;
            target.setLocation(0, 0);
            target.getParent().repaint();
        }

        public void run() {
            while(true) {
                int x = target.getX() + 5;
                int y = target.getY();
                if(x > GamePanel.this.getWidth())
                    target.setLocation(0,0);
                else
                    target.setLocation(x, y);

                target.getParent().repaint();
                try {
                    sleep(20);
                }
                catch(InterruptedException e) {
                    target.setLocation(0, 0);
                    target.getParent().repaint();
                    try {
                        sleep(500);
                    }catch(InterruptedException e2) {
                        return;
                    }
                }
            }
        }
    }

    class BulletThread extends Thread {
        JComponent bullet, target;
        Thread targetThread;
        public BulletThread(JComponent bullet, JComponent target, Thread targetThread) {
            this.bullet = bullet;
            this.target = target;
            this.targetThread = targetThread;
        }

        public void run() {
            while(true) {
                if(hit()) {
                    targetThread.interrupt();
                    bullet.setLocation(bullet.getParent().getWidth()/2 - 5, bullet.getParent().getHeight()-50);
                    return;
                }
                else {
                    int x = bullet.getX() ;
                    int y = bullet.getY() - 5;
                    if(y < 0) {
                        bullet.setLocation(bullet.getParent().getWidth()/2 - 5, bullet.getParent().getHeight()-50);
                        bullet.getParent().repaint();
                        return; // thread ends
                    }
                    bullet.setLocation(x, y);
                    bullet.getParent().repaint();
                }
                try {
                    sleep(20);
                }
                catch(InterruptedException e) {
                    return;
                }
            }
        }

        boolean hit() {
            if(targetContains(bullet.getX(), bullet.getY()) ||
                    targetContains(bullet.getX() + bullet.getWidth(), bullet.getY()) ||
                    targetContains(bullet.getX() + bullet.getWidth() , bullet.getY()+bullet.getHeight()) ||
                    targetContains(bullet.getX(), bullet.getY()+bullet.getHeight() - 1)){
                return true;
            }
            else{
                return false;
            }
        }

        boolean targetContains(int x, int y) {
            if (((target.getX() <= x) && (target.getX() + target.getWidth() - 1 >= x)) &&
                    ((target.getY() <= y) && (target.getY() + target.getHeight() - 1 >= y))) {
                return true;
            } else {
                return false;
            }
        }
    }
}

 

6번

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

public class Chapter13 extends JFrame{
    ImageIcon img = new ImageIcon("src/Bubble.png");
    Image nImg = img.getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH);
    ImageIcon rImg = new ImageIcon(nImg);

    MyThread th;
    Chapter13() {
        setTitle("버블 게임");
        setDefaultCloseOperation(3);
        Container c = getContentPane();
        c.setLayout(null);
        c.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                th = new MyThread(c, e);
                th.start();
            }
        });
        setSize(300,300);
        setVisible(true);
    }

    class MyThread extends Thread{
        int x, y;
        JLabel label = new JLabel(rImg);
        MyThread(Container c, MouseEvent e){
            x = e.getX();
            y = e.getY();
            label.setLocation(x, y);
            label.setSize(30, 30);
            c.add(label);
            repaint();
        }
        public void run(){
            while (true){
                try{
                    y -= 5;
                    label.setLocation(x, y);
                    if(label.getY() + label.getHeight() < 0){
                        return;
                    }
                    repaint();
                    Thread.sleep(200);
                }catch (InterruptedException ex){
                    return;
                }
            }

        }
    }

    public static void main(String [] args) {
        new Chapter13();
    }
}

 

7번

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

public class Chapter13 extends JFrame {
    Thread snakeThread;
    GroundPanel p;
    public Chapter13() {
        setTitle("스네이크 움직이기");
        setDefaultCloseOperation(3);

        p = new GroundPanel();
        setContentPane(p);
        setSize(400,400);
        setVisible(true);

        p.setFocusable(true);
        p.requestFocus();

        snakeThread = new Thread(p);
        snakeThread.start();
    }

    class GroundPanel extends JPanel implements Runnable{
        static final int LEFT = 0;
        static final int RIGHT = 1;
        static final int UP = 2;
        static final int DOWN = 3;
        int direction;
        Image img;
        SnakeBody snakeBody;
        final int delay = 200;

        public GroundPanel() {
            setLayout(null);
            snakeBody = new SnakeBody();
            snakeBody.addIn(this);
            direction = LEFT;
            this.addKeyListener(new MyKeyListener());
            ImageIcon icon = new ImageIcon("src/bg.jpg");
            img = icon.getImage();

            this.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    GroundPanel.this.requestFocus();
                }
            });
        }

        public void paintComponent(Graphics g) {
            g.drawImage(img, 0,0,getWidth(), getHeight(), null);
        }

        public void run() {
            while(true) {
                try {
                    Thread.sleep(delay);
                    snakeBody.move(direction);
                }catch(InterruptedException e) {
                    return;
                }
            }
        }

        class MyKeyListener extends KeyAdapter {
            public void keyPressed(KeyEvent e) {
                switch(e.getKeyCode()) {
                    case KeyEvent.VK_LEFT:
                        direction = LEFT;
                        break;
                    case KeyEvent.VK_RIGHT:
                        direction = RIGHT;
                        break;
                    case KeyEvent.VK_UP:
                        direction = UP;
                        break;
                    case KeyEvent.VK_DOWN:
                        direction = DOWN;
                        break;
                }
            }
        }
    }

    class SnakeBody {
        private Vector<JLabel> v = new Vector<>();

        public SnakeBody() {
            ImageIcon head = new ImageIcon("src/head.jpg");
            JLabel la = new JLabel(head);
            la.setSize(head.getIconWidth(), head.getIconHeight());
            la.setLocation(100, 100);
            v.add(la);

            ImageIcon body = new ImageIcon("src/body.jpg");
            for(int i=1; i<10; i++) {
                la = new JLabel(body);
                la.setSize(body.getIconWidth(), body.getIconHeight());
                la.setLocation(100+i*20, 100);
                v.add(la);
            }
        }

        public void addIn(JPanel p) {
            for(int i = 0; i < v.size(); i++)
                p.add(v.get(i));
        }

        public void move(int direction) {
            for(int i = v.size() - 1; i>0; i--) {
                JLabel b = v.get(i);
                JLabel a = v.get(i-1);
                b.setLocation(a.getX(), a.getY());
            }
            JLabel head = v.get(0);
            switch(direction) {
                case GroundPanel.LEFT :
                    head.setLocation(head.getX() - 20, head.getY());
                    break;
                case GroundPanel.RIGHT :
                    head.setLocation(head.getX() + 20, head.getY());
                    break;
                case GroundPanel.UP :
                    head.setLocation(head.getX(), head.getY() - 20);
                    break;
                case GroundPanel.DOWN :
                    head.setLocation(head.getX(), head.getY() + 20);
                    break;
            }
        }
    }

    public static void main(String[] args) {
        new Chapter13();
    }
}

 

8번

import java.awt.*;
import java.util.Vector;
import javax.swing.*;

public class Chapter13 extends JFrame{
    MyPanel panel;
    public Chapter13(){
        setTitle("눈 내리는 샤갈의 마을");
        setDefaultCloseOperation(3);
        Container c = getContentPane();
        panel = new MyPanel();
        c.add(panel);
        setVisible(true);
        setSize(500, 500);
    }
    class MyPanel extends JPanel{
        ImageIcon icon = new ImageIcon("src/back.jpg");
        Image img = icon.getImage();
        Vector<Point> snowVector = new Vector<>();
        MyPanel(){
            MyThread thread = new MyThread();
            thread.start();
        }
        public void paintComponent(Graphics g){
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
            g.setColor(Color.WHITE);
            makeSnow();
            for(int i=0; i < snowVector.size(); i++){
                Point p = snowVector.elementAt(i);
                g.fillOval(p.x, p.y, 10, 10);
            }
        }
        public void makeSnow(){
            int fin = (this.getWidth() + this.getHeight()) / 10;
            if(snowVector.size() == 0){
                for(int i = snowVector.size(); i < fin; i++){
                    int x = (int)(Math.random()*this.getWidth());
                    int y = (int)(Math.random()*this.getHeight());
                    snowVector.add(new Point(x, y));
                }
            }
            else{
                for(int i = snowVector.size(); i < fin; i++){
                    int x = (int)(Math.random() * this.getWidth());
                    int y = 0;
                    snowVector.add(new Point(x, y));
                }
            }
        }
        class MyThread extends Thread{
            public void run() {
                while(true){
                        for(int i = 0; i < snowVector.size(); i++){
                            Point p = snowVector.elementAt(i);
                            if(p.y > panel.getHeight()){
                                snowVector.remove(i);
                            }
                            else{
                                p.setLocation(p.x, p.y + 5);
                                snowVector.set(i, p);
                            }
                        }
                        repaint();
                    try{
                        Thread.sleep(100);
                    }catch (InterruptedException e){
                        return;
                    }
                }
            }
        }
    }
    public static void main(String[] args){
        new Chapter13();
    }
}