//CustomerHandler.java
package ClientInfo;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import ClientInfo.JTable1;
import java.awt.BorderLayout;
import java.io.IOException;
import java.util.Scanner;
public class CustomerHandler extends Exception {
private static final int EXIT_ON_CLOSE = 0;
static Scanner scan = new Scanner(System.in); //스켄어를 통해 값을 입력을 받을 수 있다.
static ClientMangement clm = new ClientMangement();
static int index = -1;
static String str ="";
public static void questionView() { //원하는 작업을 호출하는 메소드
System.out.println("****************************************");
System.out.println(" 원하는 작업을 선택하세요. : ");
System.out.println(" (I)Insert, (U)Update, (D)Delete,(S)Search, (A)All_Search, (P)Prev, (N)Next,\n" +
" (O)오브젝트 작업, (J)오브젝트 다운 , \n " +
" (F)파일업, (R)파일다운, G(Graphics), (Q)Quit " );
System.out.println("******************************************");
//여기서 예외처리하자
str = scan.next(); //해당값을 받아주어야 한다.
str = str.toUpperCase().trim(); // 해당값을 무조건 대문자로 바꾸어준다.
int valueT = ClientMangement.strChak(str);
//int valueT = 2;
if (str.equalsIgnoreCase("Q")) { valueT =2; }
if (valueT== 1 ) { // 사용할 수 없는 값을 반환한다
System.out.println(" 작업 메뉴에 없는 호출정보입니다. 다시 입력해주세요.");
questionView(); //재귀함수
}
}
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException, Exception {
//메인에서 호출한다. //정보를 입력받는다
//JTabbedPane tab;
//JTable1 j1;
while(true) {
questionView();
switch(str.charAt(0)){ // 들어온 값
//object를 이용한 파일 업로드를 하자
case 'O':
clm.ObjectFileUpload();
break;
case 'J':
clm.ObjectFileDownLoad();
break;
case 'I':
System.out.println(" 고객의 정보를 입력해주세요.");
clm.clientSave();
break;
case 'D':
index = clm.searchNameCardByName();
if (index >= 0 ) {
System.out.printf(" 고객을 삭제하겠습니다 . ");
clm.deleteNameCardInfo(index);
System.out.println(" 삭제되었습니다. ");
}else {
System.out.println(" 없는 고객정보 입니다.");
}
break;
case 'U': //수정하고자 하는 고객이 있는지를 확인하라
index = clm.searchNameCardByName(); //고객SEARCHING
if (index >= 0 ) {
//고객이 존재한다면 해당고객을 update하라
clm.flag = true;
clm.sexFlag = true;
clm.updateNameCardInfo(index);
}else {
System.out.println("고객 정보가 없습니다.");
}
break;
case 'S':
//searchClient();
index = clm.searchNameCardByName();
if (index >= 0) {
clm.printClientInfo(index);
}else {
System.out.println("고객정보가 없습니다.");
}
break;
case 'A':
//모드고객을 출력하자
clm.allPrintClientInfo();
break;
case 'C': //현재고객을 출력하세요.
if (index <0 ) {
System.out.println(" 현재 고객이 없습니다. ");
}else {
clm.printClientInfo(index);
}
break;
case 'P': //이전고객의 정보를 프린트 할 수 있도록 한다.
System.out.println("이전 데이타를 출력합니다.");
if (index <= 0){
System.out.println("이전데이타가 존재하지 않습니다.");
}else {
index--;
clm.printClientInfo(index);
}
break;
case 'N':
System.out.println("다음 고객을 출력합니다.");
if (index >= ClientMangement.Clientinfo.size()-1) {
System.out.println("더이상의 고객은 존재하지 않습니다.");
}else {
index++;
clm.printClientInfo(index);
}
break;
case 'Q' :
System.out.println("프로그램을 종료합니다.");
System.exit(0);
case 'G':
JTabbedPaneTest jt = new JTabbedPaneTest();
jt.setDefaultCloseOperation(EXIT_ON_CLOSE);
break;
case 'F'://파일을 업로드하다
clm.FileUpLoadings( );
break;
case 'R'://파일을 다운로드하여 콘솔창에 띄워주다.
clm.FileDownLoading();
break;
default :
questionView();
break;
}
} //while close
}//메인메소드 close
} //현클래스 customerHandler close
//ClientInfo.java
package ClientInfo;
import java.io.Serializable;
public class ClientInfo implements Serializable{
//이클립스가 이아이디를 생성해준다.
//Update을 할때 버전을 계속 바꾸어주기 위해 아이디를 만든다.
//알파버전에서 이 시리얼를 사용했다고 하자
//프로그램 개선후 베타버전을 만들시 베타버전 아이디와 구별하여 새로운 버전에서 새로운 아이디를 불러오도록 구분자를 두는것이다.
//직렬화될때 제외시키는 것이다.transient //보여주기 싫은 은닉화를 위해서 사용한다.
private String name;
private String sex;
private String email;
private int birthday;
public ClientInfo(String name, String sex, String email, int birthday){
super();
this.name = name;
this.sex = sex;
this.email= email;
this.birthday = birthday;
}
public ClientInfo() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getBirthday() {
return birthday;
}
public void setBirthday(int birthday) {
this.birthday = birthday;
}
public String toString() {
String a = "Name = " + name + ", sex= " + sex + ", email = " + email + ", birthday = " + birthday;
return a;
}
}
//clientManagement.java
package ClientInfo;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.*;
public class ClientMangement {
//implements Serializable {
static ArrayList<ClientInfo> Clientinfo = new ArrayList<ClientInfo>();//ArrayList 객채룰 생성한다. 이는 list종류줌 하나이.
static Scanner scan = new Scanner(System.in); //scan = 입력받다 / 화면을 통해
static boolean flag = false;
static boolean sexFlag =false;
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static void clientSave() {
ClientInfo clfo = new ClientInfo(); //set을 이용하여 저장한다.
System.out.print("이름 : ");
clfo.setName( scan.nextLine().trim());
sexFlag = true;
while(sexFlag) {
System.out.print("성별 (M,F)로 표기합니다. "); //성별을 받아서 성별의 값을 chk한다.
String sexfm = scan.nextLine().trim();
if ( sexfm.length() <= 0 || sexfm == null) sexFlag = true ;
if ( sexfm.equalsIgnoreCase("M") ||sexfm.equalsIgnoreCase("F") ) {
clfo.setSex(sexfm ); sexFlag = false;
}else {
sexFlag = true;
}
}
System.out.print("이메일 : ");
clfo.setEmail(scan.nextLine().trim());
flag = true;
while (flag) {
System.out.print(" 숫자로 생년월일을 입력해주세요: ");
String select = scan.nextLine().trim();
int select1 = intReturn(select );
clfo.setBirthday(select1);
}
Clientinfo.add(clfo);
printClientInfo(Clientinfo.size()-1) ;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static void printClientInfo(int idx) {
ClientInfo cls = Clientinfo.get(idx);
//현재 리스트에 값을 출력하기 위해 출력한다
System.out.println("*****************************************");
System.out.println(" 이름은 : " + cls.getName());
System.out.println(" 성별 : " + cls.getSex());
System.out.println(" 이메일 : " + cls.getEmail());
System.out.println(" 출생년도 : " + cls.getBirthday());
System.out.println("*****************************************");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static void allPrintClientInfo( ) {
int count = Clientinfo.size();
ClientInfo ccs ;
if ( count <= 0 ) {
System.out.println(" 회원정보가 없습니다 ");
} else {
for(int i=0; i< count ; i++) {
ccs = Clientinfo.get(i);
//현재 리스트에 값을 출력하기 위해 출력한다
System.out.println("*****************************************");
System.out.println(" 이름은 : " + Clientinfo.get(i).getName() );
System.out.println(" 성별 : " + Clientinfo.get(i).getSex());
System.out.println(" 이메일 : " +Clientinfo.get(i).getEmail());
System.out.println(" 출생년도 : " + Clientinfo.get(i).getBirthday());
System.out.println("*****************************************");
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//해당고객을 지우다.
public static void deleteNameCardInfo(int idx) {
//arraylist의 remove메소드를 이용할 수 있다.
Clientinfo.remove(idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//SEARCH 해당고객이 존재하는지 찾는다.
public static int searchNameCardByName() {
System.out.print("이름을 입력하세요 : "); //찿고자 하는 이름을 검색한다
String name = scan.nextLine().trim(); //입력된 이름을 name에 저장하여
for(int i=0; i< Clientinfo.size(); i++) {
if(Clientinfo.get(i).getName().equals(name)) { //리스트에 있는 값과 방금 받은 값을 비교한다..
return i; //0과 1을 리턴
}
}
return -1;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//예외처리를 하다
public static int strChak(String val) {
//매개변수로 String val을 받는다.
//들어온값이 q이면 종료됨을 알려준다.
String str1 = "";
if (val.length() < 0 || val.length() > 1) {
return 1;
}else if(val.length() == 1) {
//한글자가 들어올때엔
//현재값을 string으로 받아서 ,을 기준으로 배열에 담아 비교할 수도 있다.
String arrString= "I,A,C,S,P,N,Q,D,U,G,F,R,O,J";
String[] arradd = arrString.split(",");
for(int i =0; i<arradd.length; i++) {
str1 = arradd[i];
if ( val.equalsIgnoreCase(str1)) {
return 2;
}
} //for문
return 1;
}//else if
return 1;
}//해당 메소드
/////////////////////////////////////////////////////////////////////////////////////////////////////
/*
public static int strChak(String val) {
//매개변수로 String val을 받는다.
//들어온값이 q이면 종료됨을 알려준다.
String str1 = "";
if (val.length() < 0 || val.length() > 1) {
return 1;
}else if(val.length() == 1) {
//한글자가 들어올때엔
//현재값을 string으로 받아서 ,을 기준으로 배열에 담아 비교할 수도 있다.
String arr[]= { "I","A","S","U","D","P","N", "C"};
for(int i =0; i<arr.length; i++) {
str1 =arr[i];
if ( val.equalsIgnoreCase(str1)) {
return 2;
}
} //for문
return 1;
}//else if
return 1;
}//해당 메소드
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////
//해당정보를 UPDATE하라
public static void updateNameCardInfo(int idx) { // 해당인덱스에 값을 Update수정한다.
System.out.println(" 고객정보를 수정합니다........");
ClientInfo cms = Clientinfo.get(idx); //수정하고자 하는 해당 인덱스의 값을 가지고 온다
///////////////////////////////////////////////////////
System.out.printf(" 이름 (%s) : " , cms.getName( ));
String name = scan.nextLine().trim(); //입력받은 값의 공백을 제거한다.
if(name != null && name.length()>=0) {
cms.setName(name);
}
System.out.printf(" 성별 (%s) :", cms.getSex());
while(sexFlag) {
System.out.print("성별 (M,F)로 표기합니다. "); //성별을 받아서 성별의 값을 chk한다.
String sex = scan.nextLine().trim();
if (sex.length() <= 0 || sex == null) sexFlag = true ;
if ( sex.equalsIgnoreCase("M") || sex.equalsIgnoreCase("F") ) { cms.setSex(sex ); sexFlag = false;}
else { sexFlag = true;}
}
///////////////////////////////////////////////////////
System.out.printf(" 이메일 (%s) :" , cms.getEmail());
String email = scan.nextLine().trim(); //입력받은 값의 공백을 제거한다.
if(email != null && email.length()>=0) {
cms.setEmail(email);
}
///////////////////////////////////////////////////////
System.out.printf(" 출생년도(%d) : " , cms.getBirthday() );
System.out.println();
while (flag) {
// 예외처리 메소드 호출문
System.out.println("숫자로 입력해주세요 : ");
String select = scan.nextLine().trim();
int select1 = intReturn(select );
cms.setBirthday(select1);
}
printClientInfo(Clientinfo.size()-1);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static int intReturn(String str) {
int selec = 0;
try {
selec = Integer.parseInt(str); //str을 받아서 무조곤 정수로 반환한다. //이를 통해 문제발생시 catch문으로 이동한다
flag = false;
} catch (NumberFormatException e) {
flag = true; //그래서 flag의 값을 true를 반환한다. 그럼 while문을 다시 돌게 된다.
return 0;
}
return selec;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//파일에 있는 값을 가지고 와서 파일에 다시 뿌려준다.
public static void FileDownLoading() {
try {
//ClientInfo clfo = new ClientInfo();
//File file = new File("C:/javawork/result.txt");
File file = new File("result.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
//파일을 찾는다,
Clientinfo.clear();
String line ="";
while ((line = br.readLine())!=null) {
if (line == null) {break; } //다시파일을 만들다.
ClientInfo clfo = new ClientInfo();
String arr[] = line.toString().trim().split(",") ;
clfo.setName(arr[0]);
clfo.setSex(arr[1] );
clfo.setEmail(arr[2]);
Integer a = new Integer(arr[3]);
clfo.setBirthday(a) ;
Clientinfo.add(clfo);
System.out.println(line.toString());
}
//배열에 담은 값을 ArrayList에 담다.
}catch(Exception e) {e.printStackTrace(); }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static void FileUpLoadings ( ) {
//리스트에 있는 값을 파일에 저장한다,
//ArrayList<String> list = new ArrayList<String>();
//이게 잘되면 예외처리로서 파일이 없으면 생성하기
try {
File outFile = new File("result.txt"); //해당파일이 있느지 없느지를 확인해보자 new File("C:/javawork/result.txt")
boolean isexists = outFile.exists();
if (isexists = false ) { outFile.createNewFile(); }
FileOutputStream fos = new FileOutputStream(outFile); //선택된 파일에 쓰기 위해서 파일을 열고
OutputStreamWriter osw = new OutputStreamWriter(fos); //선택된 파일에 스트림으로 열어서 통로를 만들고
BufferedWriter bw = new BufferedWriter(osw); //버퍼에 실어서 작성하기 위해
for(int i = 0; i < Clientinfo.size(); i++) {
String str = Clientinfo.get(i).getName() + "," + Clientinfo.get(i).getSex() + "," +
Clientinfo.get(i).getEmail() + "," + Clientinfo.get(i).getBirthday() ;
bw.write(str); //버퍼에 string을 넣는다.
bw.newLine();
}
bw.flush(); //이걸 해주지 않으면 실제 쓰여지지 않는다. 버퍼에만 썼기 때문에 //버퍼에 써준다.
System.out.println("저장되었습니다. 확이하세요");
} catch (Exception e) {
e.printStackTrace();
System.out.println("에러 발생");
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <Clientinfo> void ObjectFileDownLoad() {
try {
File file = new File("result.bin"); //이렇게 작성하면 이클립스가 깔린곳에 저장한다.
FileInputStream fis = new FileInputStream(file);
ObjectInputStream isr = new ObjectInputStream(fis);
Clientinfo = (ArrayList<ClientInfo>)isr.readObject(); //배열에이쓴값을 오브젝트화해서 리스트에 저장한다.
isr.close();
System.out.println("리스트에 저장완료");
System.out.println(Clientinfo.size());
//잘 저장이 되었는지 확인하기 위해서 콘솔창에 뜨워봄
for (int i = 0; i < Clientinfo.size(); i++) {
String str = Clientinfo.get(i).getName() + "," + Clientinfo.get(i).getSex() + "," +
Clientinfo.get(i).getEmail() + "," + Clientinfo.get(i).getBirthday() ;
System.out.println(str);
}
}catch(Exception e)
{e.printStackTrace(); }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static void ObjectFileUpload() {
try {
File outFile = new File("result.bin"); //해당파일이 있느지 없느지를 확인해보자 new File("C:/javawork/result.txt")
boolean isexists = outFile.exists();
if (isexists = false ) { outFile.createNewFile(); }
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream osw = new ObjectOutputStream(fos);
osw.writeObject(Clientinfo);
osw.close();
System.out.println("저장되었습니다. 확이하세요");
} catch (Exception e) {
e.printStackTrace();
System.out.println("에러 발생");
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//JTabbedPaneTest.java
package ClientInfo;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
//import ClientInfo.JTable1;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
public class JTabbedPaneTest extends JFrame implements ActionListener, WindowListener
{
//private static final MouseListener MouseEvent = null;
static JTabbedPane tab;
static JTable1 j1;
//static JTable2 j2;
static JButton btn;
int cnt=0;
public void setDefaultCloseOperation(int arg0) {
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public JTabbedPaneTest()
{
super("고객정보 데이타");
try {
tab = new JTabbedPane(JTabbedPane.RIGHT);
JPanel one = new JPanel();
//JPanel two = new JPanel();
JButton btn = new JButton("파일변환");
j1 = new JTable1();
// j2 = new JTable2();
one.add(j1);
// two.add(j2);
tab.addTab("고객정보", one);
// tab.addTab("직업정보", two);
this.add(btn, BorderLayout.EAST);
getContentPane().add(tab, BorderLayout.CENTER);
getContentPane().getBackground().getRGB();
getContentPane().getForeground().getBlue();
setSize(700, 700);
ListSelectionModel model = j1.table.getSelectionModel(); //선택하는 모드로 바꾸기 위한 객체선언
/* model.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if( ! model.isSelectionEmpty()) {
//int a = model.getMinSelectionIndex();
int a = j1.table.getSelectedRow();
System.out.println(a );
}//end if //
}//vlaueChanged //
}); //model*/
btn.addActionListener(this);
setVisible(true);
}catch(Exception c) {
System.out.println(c.getMessage());
}
}
@Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
;
}
@Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
String selectedData ="";
Object obj = e.getSource();
j1.table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
try {
//File outFile = new File("C:/javawork/result.txt"); //해당파일이 있느지 없느지를 확인해보자
File outFile = new File("result.txt"); //해당파일이 있느지 없느지를 확인해보자
boolean isexists = outFile.exists();
if (isexists = false ) { outFile.createNewFile(); }
FileOutputStream fos = new FileOutputStream(outFile);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
for (int i = 0; i < j1.table.getRowCount(); i++) {
for (int j = 0; j < j1.table.getColumnCount(); j++) {
if (j==0) {
selectedData = (String) j1.table.getValueAt(i,j) ;
}else {
selectedData = selectedData.trim()+ ","+ (String) j1.table.getValueAt(i,j) ; }
}//j for문 *///Selected된 것에 대한 값
bw.write(selectedData);
bw.newLine();
selectedData ="";
} //i의 for문
bw.flush(); //이걸 해주지 않으면 실제 쓰여지지 않는다. 버퍼에만 썼기 때문에
System.out.println("저장되었습니다. 확이하세요");
} catch(Exception ew) { ew.getMessage(); System.out.println("에러 발생"); }
}
}
//JTable1.java
package ClientInfo;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
//import javax.swing.text.html.HTMLDocument.Iterator;
import javax.swing.text.html.CSS;
public class JTable1 extends JPanel
{
JTable table ;
JScrollPane sp ;
//DefaultTable Model ;
public JTable1(){
ClientInfo ccs = new ClientInfo();
String title[] = {"이름", "성별", "이메일", "생년월일"};
int count = ClientMangement.Clientinfo.size();
String data[][] = new String [count][4];
System.out.println(count);
if ( count <= 0 ) {
System.out.println(" 고객정보가 없습니다. ");
} else {
for(int i=0; i< count; i++) {
ccs = ClientMangement.Clientinfo.get(i);
for (int j=0; j< 4; j++) {
data[i][0] = ccs.getName();
data[i][1] = ccs.getSex();
data[i][2] = ccs.getEmail();
data[i][3] = String.valueOf(ccs.getBirthday());
}
} // 이중 for문 close
DefaultTableModel model = new DefaultTableModel(data, title);
table = new JTable(model);
//JTable table = new JTable(data, title);
sp = new JScrollPane(table);
this.add(sp);
DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
tcr.setHorizontalAlignment(SwingConstants.CENTER);
TableColumnModel tcmSchedule = table.getColumnModel();
for (int i = 0; i < tcmSchedule.getColumnCount(); i++) {
tcmSchedule.getColumn(i).setCellRenderer(tcr);
tcmSchedule.getColumn(i).setPreferredWidth(10);
}
}////else
}//JTable1
} ////JTable1 class�� �ݴ�.