자바기초) Swing 활용 퀴즈 : 연락처 프로그램 5 (GUI)

박대현·2023년 2월 14일
0

자바 기초 활용

목록 보기
21/22

연락처 프로그램4를 수정하여 아래 그림처럼 GUI 연락처 프로그램을 만들어라.


Main (변경사항 있음)


import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTextArea;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;

public class Main {

	private JFrame frame;
	private JTextField textName;
	private JTextField textIndex;
	private JTextField textPhone;
	private JTextField textEmail;
	private JTable table;
	JTextArea textArea;
	JTextArea textArea_1;
	DefaultTableModel model;
	private ContactDAO dao;
	private final String[] header = { "Index", "Name", "Phone", "Email" }; // 테이블 헤더 항목 설정

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Main window = new Main();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Main() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		dao = ContactDAOImple.getInstance(); // 싱글톤 패턴
		frame = new JFrame();
		frame.setBounds(100, 100, 639, 599);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		JLabel lblTitle = new JLabel("연락처 프로그램");
		lblTitle.setFont(new Font("굴림", Font.BOLD, 40));
		lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblTitle.setBounds(12, 10, 599, 50);
		frame.getContentPane().add(lblTitle);

		JLabel lblName = new JLabel("이름");
		lblName.setFont(new Font("굴림", Font.BOLD, 30));
		lblName.setBounds(33, 69, 128, 50);
		frame.getContentPane().add(lblName);

		JLabel lblPhone = new JLabel("전화번호");
		lblPhone.setFont(new Font("굴림", Font.BOLD, 30));
		lblPhone.setBounds(33, 127, 128, 50);
		frame.getContentPane().add(lblPhone);

		JLabel lblEmail = new JLabel("이메일");
		lblEmail.setFont(new Font("굴림", Font.BOLD, 30));
		lblEmail.setBounds(33, 187, 128, 50);
		frame.getContentPane().add(lblEmail);

		textName = new JTextField();
		textName.setFont(new Font("굴림", Font.PLAIN, 20));
		textName.setBounds(173, 69, 206, 50);
		frame.getContentPane().add(textName);
		textName.setColumns(10);

		textPhone = new JTextField();
		textPhone.setFont(new Font("굴림", Font.PLAIN, 20));
		textPhone.setColumns(10);
		textPhone.setBounds(173, 127, 206, 50);
		frame.getContentPane().add(textPhone);

		textEmail = new JTextField();
		textEmail.setFont(new Font("굴림", Font.PLAIN, 20));
		textEmail.setColumns(10);
		textEmail.setBounds(173, 187, 206, 50);
		frame.getContentPane().add(textEmail);

		JButton btnInsert = new JButton("등록");
		btnInsert.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) {
				textArea.setText(""); // 이전 출력 문구 제거
				textArea_1.setText("");  // 이전 출력 문구 제거
                //입력 값 받아오기
				String name = textName.getText(); 
				String phone = textPhone.getText();
				String email = textEmail.getText();
				ContactVO vo = new ContactVO(name, phone, email); 
				int result = dao.insert(vo); //등록할 정보 전달
				if (result == 1) { // 등록이 성공하면
					int index = ((ContactDAOImple) dao).getListSize() - 1;
					String[] rows = new String[4];
					rows[0] = String.valueOf(index);
					rows[1] = vo.getName();
					rows[2] = vo.getPhone();
					rows[3] = vo.getEmail();
					model.addRow(rows); //행을 채운다.
					textArea_1.setText(((ContactDAOImple) dao).getListSize() - 1 + "번 인덱스에 연락처가 등록 되었습니다."); //등록 성공 문구 출력
				}

			}
		});
		btnInsert.setBounds(33, 247, 97, 40);
		frame.getContentPane().add(btnInsert);

		textIndex = new JTextField();
		textIndex.setBounds(142, 247, 97, 40);
		frame.getContentPane().add(textIndex);
		textIndex.setColumns(10);

		JButton btnUpdate = new JButton("수정"); 
		btnUpdate.addActionListener(new ActionListener() { //수정 버튼에 액션 발생시
			public void actionPerformed(ActionEvent e) {
				textArea.setText(""); // 이전 출력 문구 제거
				textArea_1.setText(""); // 이전 출력 문구 제거
				if (!textIndex.getText().equals("")) { //인덱스 값을 입력 한 경우
					int index = Integer.parseInt(textIndex.getText());
					if (index >= 0 && index < ((ContactDAOImple) dao).getListSize()) {
						String name = textName.getText();
						String phone = textPhone.getText();
						String email = textEmail.getText();
						ContactVO vo = new ContactVO(name, phone, email);
						int result = dao.update(index, vo);
						if (result == 1) { // 수정 성공 시
							textArea_1.setText(index + "번 인덱스의 연락처가 수정 되었습니다.");
                            // 해당 행 값 수정
							table.setValueAt(name, index, 1);
							table.setValueAt(phone, index, 2);
							table.setValueAt(email, index, 3);
						}
					}
				} else { // 인덱스 값 입력 안한 경우 경고 문구 출력
					textArea_1.setText("인덱스를 확인 해주세요.");
				}

			}
		});
		btnUpdate.setBounds(33, 297, 97, 40);
		frame.getContentPane().add(btnUpdate);

		JButton btnDelete = new JButton("삭제");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textArea.setText("");
				textArea_1.setText("");
				if (!textIndex.getText().equals("")) {
					int index = Integer.parseInt(textIndex.getText());
					if (index >= 0 && index < ((ContactDAOImple) dao).getListSize()) {
						int result = dao.delete(index);
						if (result == 1) { // 삭제 성공 시
							textArea_1.setText(index + "번 인덱스의 연락처가 삭제 되었습니다.");
							model.removeRow(index); //해당 행 삭제
                            
                            //인덱스 값 새로고침
							ArrayList<ContactVO> list = dao.select(); 
							for (int i = 0; i < list.size(); i++) {
								table.setValueAt(String.valueOf(i), i, 0);
							}
						}
					}
				} else {
					textArea_1.setText("인덱스를 확인 해주세요.");
				}

			}
		});
		btnDelete.setBounds(141, 297, 97, 40);
		frame.getContentPane().add(btnDelete);

		JButton btnAllSearch = new JButton("전체검색");
		btnAllSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textArea.setText("");
				textArea_1.setText("");
				ArrayList<ContactVO> list = dao.select();
				for (int i = 0; i < list.size(); i++) {
					textArea.append(list.get(i).toString() + "\n"); // 연락처 명부 전체 출력
				}
			}
		});
		btnAllSearch.setBounds(245, 297, 97, 40);
		frame.getContentPane().add(btnAllSearch);

		JButton btnSearch = new JButton("검색");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textArea.setText("");
				textArea_1.setText("");
				if (!textIndex.getText().equals("")) {
					int index = Integer.parseInt(textIndex.getText());
					if (index >= 0 && index < ((ContactDAOImple) dao).getListSize()) {
						ContactVO vo = dao.select(index);
						textArea.setText(vo.toString());
					}
				} else {
					textArea_1.setText("인덱스를 확인 해주세요.");
				}

			}
		});
		btnSearch.setBounds(245, 247, 97, 40);
		frame.getContentPane().add(btnSearch);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(33, 350, 309, 69);
		frame.getContentPane().add(scrollPane);

		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);

		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(33, 429, 309, 69);
		frame.getContentPane().add(scrollPane_1);

		textArea_1 = new JTextArea();
		scrollPane_1.setViewportView(textArea_1);

		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(354, 247, 257, 251);
		frame.getContentPane().add(scrollPane_2);
		
        //테이블 해더 추가
		model = new DefaultTableModel(header, 0);
		table = new JTable(model);
		scrollPane_2.setViewportView(table); 
        
        //이전에 저장되어 있던 연락처 명부 테이블에 추가
		ArrayList<ContactVO> list = dao.select();
		for (int i = 0; i < list.size(); i++) {
			String[] rows = new String[4];
			rows[0] = String.valueOf(i);
			rows[1] = list.get(i).getName();
			rows[2] = list.get(i).getPhone();
			rows[3] = list.get(i).getEmail();
			model.addRow(rows); 
		}

	}
}

ContactVO (변경사항 없음)


import java.io.Serializable;

public class ContactVO implements Serializable {
	private String name;
	private String phone;
	private String email;

	public ContactVO() {

	}

	public ContactVO(String name, String phone, String email) {
		this.name = name;
		this.phone = phone;
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return "ContactVO [name=" + name + ", phone=" + phone + ", email=" + email + "]";
	}

}

ContactDAO (변경사항 없음)


import java.util.ArrayList;

public interface ContactDAO {
	public abstract int insert(ContactVO vo);

	public abstract ArrayList<ContactVO> select();

	public abstract ContactVO select(int index);

	public abstract int update(int index, ContactVO vo);
	
	public abstract int delete(int index);
}

ConTactDAOImple (변경사항 없음)

package edu.java.contact05;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class ContactDAOImple implements ContactDAO {

	private static ContactDAOImple instance = null;

	private ContactDAOImple() { // 싱글톤 객체 초기화 시 바로 파일 확인 하도록 함.
		initDataDir();
		initDataFile();
	}

	public static ContactDAOImple getInstance() {
		if (instance == null) {
			instance = new ContactDAOImple();
		}
		return instance;
	}

	private ArrayList<ContactVO> list = new ArrayList<>(); // 연락처 저장 장소

	// 데이터를 저장할 폴더와 파일 이름 정의
	private static final String DATA_DIR = "data";
	private static final String DATA_FILE = "contact.data";

	// data 폴더의 contact.data 파일을 관리할 File 객체 선언
	private File dataDir;
	private File dataFile;

	// TODO : data 폴더가 있는지 검사하고, 없으면 생성하는 함수
	private void initDataDir() {
		System.out.println("initDataDir()");
		dataDir = new File(DATA_DIR);
		System.out.println("폴더 경로 : " + dataDir.getPath());
		System.out.println("절대 경로 : " + dataDir.getAbsolutePath());
		if (!dataDir.exists()) { // 폴더가 없으면
			System.out.println("폴더가 생성되지 않았습니다.");
			if (dataDir.mkdirs()) {
				System.out.println("폴더 생성 성공");
			} else {
				System.out.println("폴더 생성 실패");
			}
		} else {
			System.out.println("폴더가 이미 존재");
		}
	} // end initDataDir()

	// TODO : 데이터 파일이 존재하는지 검사하고,
	// 없는 경우 - 새로운 데이터 파일 생성
	// 있는 경우 - 기존 파일에서 데이터를 읽어서 ArrayList에 추가
	private void initDataFile() {
		dataFile = new File(DATA_DIR + File.separator + DATA_FILE);
		System.out.println("파일 경로 : " + dataFile.getPath());
		System.out.println("절대 경로 : " + dataFile.getAbsolutePath());
		if (!dataFile.exists()) { // 파일이 없을 때
			System.out.println("파일이 생성되지 않았습니다.");
			try {
				if (dataFile.createNewFile()) {
					System.out.println("파일 생성 성공");
				} else {
					System.out.println("파일 생성 실패");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else { // 파일이 있을 때
			System.out.println(list.size());
			if (list.size() != 0) {
//			if (dataFile.length()!=0) {
				readDataFromFile();
			}
			System.out.println("파일이 이미 존재 합니다.");
		}
	}

	OutputStream out = null;
	BufferedOutputStream bout = null;
	ObjectOutputStream oout = null;

	// TODO : 멤버 변수 list 객체를 data\contact.data 파일에 저장(쓰기)
	private void writeDataToFile() {
		try {
			out = new FileOutputStream(DATA_DIR + File.separator + DATA_FILE);
			bout = new BufferedOutputStream(out);
			oout = new ObjectOutputStream(bout);
			oout.writeObject(list);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				oout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	} // end writeDataToFile()

	// TODO : data\contact.data 파일에서 ArrayList 객체를 읽어와서
	// 멤버 변수 list에 저장(읽기)
	InputStream in = null;
	BufferedInputStream bin = null;
	ObjectInputStream oin = null;

	private void readDataFromFile() {
		try {
			in = new FileInputStream(DATA_DIR + File.separator + DATA_FILE);
			bin = new BufferedInputStream(in);
			oin = new ObjectInputStream(bin);
			list = (ArrayList<ContactVO>) oin.readObject();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				oin.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	} // end readDataFromFile()

	public int getListSize() {
		return list.size();
	}

	@Override
	public int insert(ContactVO vo) {
		list.add(vo);
		writeDataToFile();
		return 1; // 0 : 실패, 1 : 성공
	}

	@Override
	public ArrayList<ContactVO> select() {
		readDataFromFile();
		return list;
	}

	@Override
	public ContactVO select(int index) {
		readDataFromFile();
		return list.get(index);
	}

	@Override
	public int update(int index, ContactVO vo) {
		// list.set(index, new ContactVO(vo.getName(), vo.getPhone(), vo.getEmail()));
		list.get(index).setEmail(vo.getEmail());
		list.get(index).setName(vo.getName());
		list.get(index).setPhone(vo.getPhone());
		writeDataToFile();
		return 1;
	}

	@Override
	public int delete(int index) {
		list.remove(index);
		writeDataToFile();
		return 1;
	}

}

0개의 댓글