본문 바로가기
솔루션모음/파워자바 프로그래밍

[파워자바] 17장 프로그래밍 솔루션 답지

by 이얏호이야호 2023. 2. 16.

 

1.

 
import java.awt.*;
import java.awt.event.*;
 
import javax.swing.*;
 
public class NumberGameextends JFrame {
       private int randomNum;
       private JTextField inputField;
       private JLabel guideLabel;
       private JButton retryButton;
       private JButton exitButton;
 
       public NumberGame(){
             //부모 클래스 생성자 명시적 호출
              super("숫자게임");
 
              //top 패널에 들어갈 컴포넌트 구성
              JLabel infoLabel = new JLabel("숫자를 추측하시오 : ");
              inputField = new JTextField(10);
              inputField.addActionListener(new TextFieldActionListener());
 
              //top 패널 구성
              JPanel topPanel = new JPanel();
              topPanel.add(infoLabel);
              topPanel.add(inputField);
 
              //middle 패널에 들어갈 레이블 구성
              guideLabel = new JLabel("숫자를 입력하시오.");
              guideLabel.setBackground(Color.WHITE);
              guideLabel.setOpaque(true);//레이블을 불투명하게
 
              //middle 패널 구성
              JPanel middlePanel = new JPanel();
              middlePanel.add(guideLabel);
 
              //low 패널에 들어갈 버튼 구성
              retryButton = new JButton("새 게임");
              exitButton = new JButton("종료");
              retryButton.addActionListener(new ButtonActionListener());
              exitButton.addActionListener(new ButtonActionListener());
 
              //low 패널 구성
              JPanel lowPanel = new JPanel();
              lowPanel.add(retryButton);
              lowPanel.add(exitButton);
 
              //메인 패널 구성
              JPanel mainPanel = new JPanel();
              mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
              mainPanel.add(topPanel);
              mainPanel.add(middlePanel);
              mainPanel.add(lowPanel);
              add(mainPanel);
 
              //랜덤 넘버와 프레임 설정
              setRandomNum();
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
              setVisible(true);
       }
       //TextField에 들어갈 액션 리스너
       private class TextFieldActionListener implements ActionListener{
             @Override
             public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    try{
                           if(Integer.parseInt(inputField.getText()) < randomNum){
                                 guideLabel.setText("너무 낮습니다!");
                                 guideLabel.setBackground(Color.RED);
                           }
                           else if(Integer.parseInt(inputField.getText()) > randomNum){
                                 guideLabel.setText("너무 높습니다!");
                                 guideLabel.setBackground(Color.RED);
                           }
                           else{
                                 guideLabel.setText("정답입니다!");
                                 guideLabel.setBackground(Color.WHITE);
                           }
                    }
                    catch(NumberFormatException ne){
                           guideLabel.setText("잘못된 입력입니다!");
                           guideLabel.setBackground(Color.RED);
                    }
                    inputField.selectAll();
             }
       }
       //Button에 들어갈 액션 리스너
       private class ButtonActionListener implements ActionListener{
             @Override
             public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    if(e.getSource() == retryButton){
                           setRandomNum();
                           guideLabel.setText("숫자를 입력하시오.");
                           inputField.setText("");
                    }
                    else if(e.getSource() == exitButton){
                           System.exit(0);
                    }
             }
       }
       //접근자
       public int getRandomNum() {return randomNum;}
       //설정자
       public void setRandomNum() {randomNum = (int)(Math.random()*100)+1;}
       public static void main(String[] args){
             new NumberGame();
       }
}

 

2.

import java.awt.*;
import java.awt.event.*;
 
import javax.swing.*;
 
public class TextConverter extends JFrame {
       JButton converter;
       JButton canceler;
       JTextArea textIn;
       JTextArea textOut;
 
       public TextConverter(){
             super("텍스트 변환");
 
             //텍스트 에어리어
             textIn = new JTextArea(10, 14);
             textOut = new JTextArea(10, 14);
             textIn.setLineWrap(true);//자동 줄바꿈
             textOut.setLineWrap(true);
             textOut.setEnabled(false);//비활성화
             
             //텍스트 에어리어를 관리할 패널
             JPanel textAreaPanel = new JPanel(new GridLayout(1, 2, 20, 20));
             textAreaPanel.add(textIn);
             textAreaPanel.add(textOut);
             
             //버튼
             converter = new JButton("변환");
             canceler = new JButton("취소");
             converter.addActionListener(new ButtonActionListener());
             canceler.addActionListener(new ButtonActionListener());
             
             //버튼 패널
             JPanel buttonPanel = new JPanel(new FlowLayout());
             buttonPanel.add(converter);
             buttonPanel.add(canceler);
 
             //메인 패널
             JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
             mainPanel.add(BorderLayout.CENTER, textAreaPanel);
             mainPanel.add(BorderLayout.SOUTH, buttonPanel);
             
             //프레임 설정
             setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20));
             add(mainPanel);
             pack();
             setDefaultCloseOperation(EXIT_ON_CLOSE);
             setVisible(true);
       }
       
       //버튼의 액션 이벤트를 처리 할 버튼 액션 리스너 클래스
       private class ButtonActionListener implements ActionListener{
             @Override
             public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    if(e.getSource() == converter){
                           textOut.setText("");
                           String result = toEnglish(textIn.getText());
                           textOut.append(result);
                    }
                    if(e.getSource() == canceler){
                           textOut.setText("");
                    }
             }
             //영어를 한국어로 변환하는 메소드 
             private String toEnglish(String korean){
                    String result = korean;
                    result = result.replace("텍스트", "Text");
                    result = result.replace("영어", "English");
                    return result;
             }
       }
       public static void main(String[] args){
             TextConverter t=new TextConverter();
       }
 }

 

3.

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class CheckBoxDemo extends JPanel implements ItemListener {
	JCheckBox[] buttons = new JCheckBox[4];
	String[] fruits = { "엔진오일 교환", "자동변속기오일교환", "에어콘필터교환", "타이어 교환"};
	int[] prices = { 45000, 80000, 30000, 100000 };
	int money=0;
	JLabel label;
	
	public CheckBoxDemo() {
		super();
		// 체크 박스 생성
		for (int i = 0; i < 4; i++) {
			buttons[i] = new JCheckBox(fruits[i]);
			buttons[i].addItemListener(this);
		}
		for (int i = 0; i < 4; i++)
			add(buttons[i]);
		label = new JLabel("현재까지의 가격은"+money+"입니다.");
		label.setFont(new Font("Serif", 	// 레이블에 폰트를 설정한다. 
				Font.BOLD | Font.ITALIC, 30)); 
		add(label);
	}

	/** 체크 박스의 아이템 이벤트를 처리한다. */
	public void itemStateChanged(ItemEvent e) {
		Object source = e.getItemSelectable();
		for (int i = 0; i < 4; i++) {
			if (source == buttons[i]) {
				if (e.getStateChange() == ItemEvent.DESELECTED)
					money -= prices[i];
				else
					money += prices[i];
				label.setText("현재까지의 가격은"+money+"입니다.");
			}
		}
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame("CheckBoxDemo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JComponent newContentPane = new CheckBoxDemo();
		newContentPane.setOpaque(true); 
		frame.setContentPane(newContentPane);
		frame.setSize(500, 200);
		frame.setVisible(true);
	}
}

5.

 
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

class MyPanel extends JPanel
{
	private static final int EMPTY = 0,X_PIECE = 1,O_PIECE = 2;
	private int[][] gameGrid = new int[3][3]; 
	private boolean xTurn; 
	private Random random; 
	private boolean gameRunning; 
	private int gameResult; 

	public MyPanel()
	{
		setPreferredSize(new Dimension(256,256));
		setBackground(Color.WHITE);
		addMouseListener(new GameListener());
		random = new Random();
		clearGrid();
		gameRunning = true;
	}
	private class GameListener implements MouseListener
	{
		public void mousePressed(MouseEvent e){}
		public void mouseClicked(MouseEvent e)
		{
			int xPos = e.getPoint().x;
			int yPos = e.getPoint().y;
			if(xPos > 50 && yPos > 50 && xPos < 50+50*3 && yPos < 50+50*3)
			{
				if(gameRunning == false)
				{
					clearGrid();
					gameRunning = true;
					repaint();
					return;
				}
				if(gameGrid[xPos/50-1][yPos/50-1] != EMPTY)
					return; 
				if(xTurn)
				{
					gameGrid[xPos/50-1][yPos/50-1] = X_PIECE;
					xTurn = false;
				}
				else
				{
					gameGrid[xPos/50-1][yPos/50-1] = O_PIECE;
					xTurn = true;
				}
				gameResult = gameOver();
				if(gameResult != 0)
				{
					gameRunning = false;
				}
				repaint();
			}
		}
		public void mouseReleased(MouseEvent e){}
		public void mouseEntered(MouseEvent e){}
		public void mouseExited(MouseEvent e){}
	}
	public void clearGrid()
	{
		for(int y = 0;y < 3;y++)
			for(int x = 0;x < 3;x++)
				gameGrid[x][y] = EMPTY;
		if(random.nextInt(100) < 50)
			xTurn = true;
		else
			xTurn = false;
	}
	int gameOver()
	{
		for(int x = 0;x < 3;x++) 
			if(gameGrid[x][0] == gameGrid[x][1] && gameGrid[x][1] == gameGrid[x][2])
				return gameGrid[x][0];
		for(int y = 0;y < 3;y++) 
			if(gameGrid[0][y] == gameGrid[1][y] && gameGrid[1][y] == gameGrid[2][y])
				return gameGrid[0][y];
		if(gameGrid[0][0] == gameGrid[1][1] && gameGrid[1][1] == gameGrid[2][2])
			return gameGrid[0][0];
		if(gameGrid[2][0] == gameGrid[1][1] && gameGrid[0][2] == gameGrid[1][1])
			return gameGrid[2][0];
		for(int y = 0;y < 3;y++)
			for(int x = 0;x < 3;x++)
				if(gameGrid[x][y] == 0)
					return 0; 
		return 3;
	}
	public void paintComponent(Graphics g)
	{
		g.clearRect(0,0,getWidth(),getHeight());
		g.setColor(Color.BLACK);
		for(int y = 1;y < 3;y++)
			g.drawLine(50,y*50+50,50+50*3,y*50+50);
		for(int x = 1;x < 3;x++)
			g.drawLine(x*50+50,50,x*50+50,50+50*3);
		for(int y = 0;y < 3;y++)
		{
			for(int x = 0;x < 3;x++)
			{
				if(gameGrid[x][y] == X_PIECE)
				{
					g.setColor(Color.BLUE);
					g.drawLine(50+x*50,50+y*50,50+x*50+50,50+y*50+50);
					g.drawLine(50+50+x*50,50+y*50,50+x*50,50+y*50+50);
				}
				if(gameGrid[x][y] == O_PIECE)
				{
					g.setColor(Color.RED);
					g.drawOval(50+x*50,50+y*50,50,50);
				}
			}
		}
		g.setColor(Color.BLACK);
		if(gameRunning)
		{
			if(xTurn)
				g.drawString("X 차례입니다.",10,220);
			else
				g.drawString("O 차례입니다.",10,220);
		}
		else
		{
			if(gameResult == X_PIECE)
				g.drawString("X가 이겻습니다!",10,220);
			if(gameResult == O_PIECE)
				g.drawString("O가 이겼습니다!",10,220);
			if(gameResult == 3)
				g.drawString("비겼습니다!",10,220);
			g.drawString("새로운 게임을 시작하려면 클릭하세요.",10,240);
		}
	}
}
public class TicTacToeGame extends JFrame
{
	public static void main(String[] args)
	{
		TicTacToeGame ticTacToe = new TicTacToeGame();
		ticTacToe.setTitle("tic-tac-toe");
		ticTacToe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		MyPanel gameBoard = new MyPanel();
		ticTacToe.add(gameBoard);
		ticTacToe.pack();
		ticTacToe.setLocationRelativeTo(null);
		ticTacToe.setVisible(true);
	}
}

 

 

6.

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

class Login extends JFrame implements ActionListener {
	JButton SUBMIT;
	JPanel panel;
	JLabel label1, label2;
	final JTextField text1, text2;

	Login() {
		label1 = new JLabel();
		label1.setText("이메일");
		text1 = new JTextField(30);

		label2 = new JLabel();
		label2.setText("비밀번호");
		text2 = new JPasswordField(30);

		SUBMIT = new JButton("로그인");

		panel = new JPanel(new GridLayout(0, 1));
		panel.add(label1);
		panel.add(text1);
		panel.add(label2);
		panel.add(text2);
		panel.add(SUBMIT);
		add(panel, BorderLayout.CENTER);
		SUBMIT.addActionListener(this);
		setTitle("LOGIN FORM");
	}

	public void actionPerformed(ActionEvent ae) {
		String value1 = text1.getText();
		String value2 = text2.getText();
		if (value1.equals("hong") && value2.equals("1111")) {
			System.out.println("로그인 성공");
		} else {
			System.out.println("로그인 실패");
		}
	}
}

public class LoginDemo {
	public static void main(String arg[]) {
			Login frame = new Login();
			frame.setSize(400, 200);
			frame.setVisible(true);
	}
}

댓글