본문 바로가기
코리아 IT아카데미/Java

12일차 | 예외 처리 swing 객체 지향 기법 연습

by Sharon kim 2021. 11. 2.
chapter04 복습 순서 메모
ch03>
ExceptionEx1
ExceptionEx2
ExceptionEx3
ExceptionEx4
ch04>
MyFrame1
MyFrame2
MyFrame3
MyFrame4

https://blog.naver.com/devnote1/222425528882
log : 텍스트 파일에 기록을 남기는 것

예외처리

package ch03;

public class ExceptionEx1 {

	public static void main(String[] args) {
		
		//예외를 발생 시켜 보자
		
		int[] arr = {1, 2, 3, 4, 5};
		//runtime exception
//		for (int i = 0; i < 10; i++) {
//			System.out.println(arr[i]);
//		}
		try{
			//예외가 발생할 코드를 try문에 작성을 한다.
			for (int i = 0; i < 10; i++) {
				System.out.println(arr[i]);	
			}
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("예외가 발생함");
		}
	
 		System.out.println("비정상 종료되지 않았습니다.");
 		
 		//프로그래밍이 종료되지 않고 계속 실행 되어 진다. !!!
 		
	}//end of main

}//end of class

예외처리2

package ch03;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionEx2 {

	public static void main(String[] args) {
		
		FileInputStream fis;
		
		try {
			fis = new FileInputStream("a.txt");
			//FileNotFoundException -> 파일을 찾을 수 없습니다.
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("파일을 찾을 수 없습니다.");
		} catch (Exception e) {
			System.out.println("예외 처리");
			return; //심지어 리턴(반환 혹은 실행종료)문이 있어도 finally가 실행된다.
		} finally {
			//try문이 실행되면 반드시 실행 됨
			System.out.println("반드시 실행됩니다.");
		}
		System.out.println("비정상 종료가 되지 않았습니다.");
		
		
	}//end of main

}//end of class

예외처리3

package ch03;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

class MyException{
	
	String fileName;
	
	public MyException(String fileName) {
		this.fileName = fileName;
	}
	//throws란 예외 처리 미루기
	public String readFile() throws IOException {
									
		FileInputStream fis = new FileInputStream(fileName);
		Properties prop = new Properties();
		//ctrl +shift + o
		prop.load(fis);
		String dbType =prop.getProperty("DBTYPE");
		return dbType;

	}
}

public class ExceptionEx3 {

	public static void main(String[] args) {
		
		//객체생성
		MyException exception = new MyException("a.txt");
		
		//throws가  있으면? 사용하는 입장에서 예외처리를 직접 해결해야한다.
		try {
			String temp = exception.readFile();
			System.out.println("temp : " + temp);
		} catch (IOException e) {
			System.out.println("파일이 없습니다. 파일을 확인해 주세요.");
		}
		
		Scanner scanner = null;
		
		try {
			scanner = new Scanner(System.in);
			int userInput = scanner.nextInt();
		} catch (Exception e) {
			System.out.println("예외 발생");
		}finally {
			scanner.close();
		}
		
	}//end of main

}//end of class

예외처리4

package ch03;

import java.util.logging.Logger;

class Student{
	String name;
	int grade;
}

public class ExceptionEx4 {

	public static void main(String[] args) {
		
		//로그 남기기
		Logger logger = Logger.getLogger("myLogger");
		Student student = null;
		
		try {
			student.name = "홍길동";
		} catch (Exception e) {
			System.out.println("오류 발생");
			logger.warning("오류발생" + e.toString());
		}
		
		System.out.println("비정상 종료 되지않음!!!");

	}

}

2D test

package ch04;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

class MyPanel extends JPanel{
	Image img = Toolkit.getDefaultToolkit().getImage("C:\\Users\\ITPS
    		\\Desktop\\html(jk)" + " (2)\\images\\bg_main_bnn2.jpg");
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		
		g.drawString("안녕하세요", 10, 20);
//		g.drawLine(20, 30, 100, 100);//선을 긋다 , x축 , y축
//		g.drawRect(100, 100, 150, 150);
		g.drawLine(200, 200, 325, 30);
		g.drawLine(450, 200, 325, 30);
		g.drawRect(200, 200, 250, 250);
		g.drawRect(320, 250, 100, 200);
		g.drawImage(img, 30, 40, this);

	}
}

public class MyFrame1 extends JFrame{

	MyPanel myPanel;
	
	//생성자
	public MyFrame1() {
		initData();
		setInitLayout();
	}
	//메서드 2개 만들어 주세요
	private void initData() {
		setTitle("java 2D Test");
		setSize(600, 600);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		myPanel = new MyPanel();
	}
	private void setInitLayout() {
		setVisible(true);
		add(myPanel);
	}
	
	//내부 클래스 , static(정적 내부 클래스),(인스턴스, 내부 클래스)
	static class MyPanel extends JPanel{
		
		@Override
		public void paint(Graphics g) {
			g.drawLine(20, 30, 100, 100);
			g.drawRect(100, 100, 150, 150);
			g.drawLine(200, 200, 325, 30);
		}
	}
	
	//메인함수 작성
	public static void main(String[] args) {
		new MyFrame1();
	}
}//class

패널연습

package ch04;
import java.awt.*;
import java.awt.GridLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;

public class MyFrame2 extends JFrame {
	
	JPanel JPanel1;
	JPanel JPanel2;
	JButton button1;
	JButton button2;
	
	public MyFrame2() {
		initData();
		setInitLayout();
	}
	private void initData() {
		setTitle("패널연습");
		setSize(400, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel1 = new JPanel();
		JPanel2 = new JPanel();
		button1 = new JButton("button1");
		button2 = new JButton("button2");
		
	}
	private void setInitLayout() {
		setVisible(true);
		setLayout(new GridLayout(2,1));
		add(JPanel1);
		add(JPanel2);
		
		JPanel1.setBackground(Color.yellow);
		JPanel2.setBackground(Color.blue);
		
		JPanel1.setLayout(new FlowLayout(FlowLayout.LEFT));
		JPanel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
		
		JPanel1.add(button1);
		JPanel2.add(button2);
		
	}
	public static void main(String[] args) {
		new MyFrame2();
	}
}

이미지 패널연습

package ch04;

import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

class ImagePanel extends JPanel {
	// ctrl + shift + o
	private Image image;
	private Image image2;
	//멤버변수 선언 이미지명을 받는 녀석
	
	public ImagePanel(String imageName) {
		image = new ImageIcon(imageName).getImage();
	}
	
	public ImagePanel() {
		image = new ImageIcon("images.png").getImage();
	}
	
	// paint + ctrl space
	@Override
	public void paint(Graphics g) {
		super.paint(g); // 패널의 가로 크기 만큼, 세로크기만큼
		g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
		g.drawImage(image2, 0, 0, getWidth(), getHeight(), null);
	}
}
//------------------------------------------------------------------

public class MyFrame3 extends JFrame {

	private ImagePanel imagePanel;
	private ImagePanel imagePanel2;
	private JButton button;
	//추가
	//수정
	public MyFrame3() {
		initData();
		setInitLayout();
	}

	private void initData() {
		setTitle("J패널에 이미지 넣기");
		setSize(500, 500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		imagePanel = new ImagePanel();
		imagePanel2 = new ImagePanel("images2.png");
		button = new JButton("버튼입니다.");
	}

	private void setInitLayout() {
		setVisible(true);
		setLayout(new GridLayout(2,1));
		add(imagePanel);
		add(imagePanel2);
		imagePanel.add(button);
	}

	public static void main(String[] args) {
		new MyFrame3();
	}
}// end of class

배경이미지 패널연습

package ch04;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyFrame4 extends JFrame{

	BufferedImage backgroundImage;
	MyImagePanel myImagePanel;

	//생성자
	public MyFrame4() {
		initData();
		setInitLayout();
	}
	//initData
	private void initData() {
		setTitle("이미지 백그라운드 연습");
		setSize(500, 500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		try {
			backgroundImage = ImageIO.read(new File("images.png"));
			
		} catch (IOException e) {
			System.out.println("파일을 찾을 수 없습니다.");
		}
		//myImagePanel 생성
		myImagePanel = new MyImagePanel();
		
	}
	//setInitLayout
	private void setInitLayout() {
		setVisible(true);
		add(myImagePanel);
	}
	
	private class MyImagePanel extends JPanel{
		
		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			
			g.drawImage(backgroundImage, 0, 0, 500, 500, null);
			
		}
	}//end of inner class
	
	//메인함수
	public static void main(String[] args) {
		new MyFrame4();

	}//end of main

}//end of class