Cute Apple
본문 바로가기
개발/java

java 쇼핑몰 GUI(3)

by 미댕댕 2021. 5. 24.

step 11

1. 파일 미리보기 창 디자인 변경

 

<작업 결과물>

 

- ProductMain.java 추가/변경 코드

 

 

step 12

1. 파일 찾기 클릭시 chooser을 이용하여 파일을 찾은 뒤 미리보기로 가져오자

  - Canvas 의 재사용성의 거의 없기 때문에 익명함수로 Canvas를 재정의한다.

  - 파일 찾기 버튼 클릭시 findLocal 함수 동작하는 리스너 연결

  - 자주 사용할 메서드는 클래스로 만들어 라이브러리처럼 사용한다.(FileManager 생성)

 

<작업 파일>

<작업 결과물 >

 

 

- ProductMain.java 추가/변경 코드

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//로컬 시스템에서 파일 찾아서 이미지 미리보기 구현
    public void findLocal() {
        FileInputStream fis=null;
        FileOutputStream fos=null;
        
        if(chooser.showOpenDialog(this.getAppMain())==JFileChooser.APPROVE_OPTION) {
            File file=chooser.getSelectedFile();
            
            image=kit.getImage(file.getAbsolutePath());
            can.repaint();
            
            //유저가 선택한 파일을 data 디렉토리로 복사해보자
            try {
                fis=new FileInputStream(file);
                long time=System.currentTimeMillis();
                filename=time+"."+FileManager.getExtend(file.getAbsolutePath(),"\\");
                fos=new FileOutputStream("C:\\koreaIT\\javaworkspace\\ShoppingApp\\data\\"+filename); //복사될 경로
                
                //입력과 출력스트림이 준비되었으므로, 복사를 시작하자
                int data=-1;
                byte[] buff=new byte[1024]; //1kbyte 의 버퍼 확보
                while(true) {
                    data=fis.read(buff);//버퍼로 읽었다면,
                    if(data==-1)break;
                    fos.write(buff);//버퍼로 내려쓰자
                }
                JOptionPane.showMessageDialog(this.getAppMain(), "복사완료");
                
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(fos!=null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(fis!=null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        
    }
cs

- FileManager.java 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.mijin.shopping.util;
 
//앞으로, 파일과 관련된 여러 작업을 전담하게 될 파일제어 클래스 정의
public class FileManager {
    //넘겨받은 경로를 통해 확장자만 추출해보기
    public static String getExtend(String path, String token) {
        int lastIndex=path.lastIndexOf(token);//넘겨받은 문자열내의 가장 마지막 디렉토리 구분자의 위치
//        System.out.println(lastIndex);
        
        String filename=path.substring(lastIndex+1, path.length());
        String exit=filename.substring(filename.indexOf(".")+1, filename.length());
        
        return exit;
    }
 
}
 
cs

 

 

 

step 13

1. 웹에서 소스를 찾아서 파일 가져오기

 

 

<작업 결과물>

 

- ProductMain.java 추가/변경 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//웹에서 파일 찾아서 미리보기 구현
    public void findWeb() {
        String path=JOptionPane.showInputDialog(this.getAppMain(),"경로입력");
        
        //위의 경로를 이용하여, 웹서버에 요청을 시도해본다!!
        //HttpURLConnection!!
        URL url=null;
        HttpURLConnection httpCon=null;
        InputStream is=null//입력스트림 계열의 최상위 객체
        FileOutputStream fos=null//파일을 대상으로 한 출력 스트림
        
        try {
            url=new URL(path);
            httpCon=(HttpURLConnection)url.openConnection();
            httpCon.setRequestMethod("GET");
            
            is=httpCon.getInputStream(); //웹서버의 요청에 연결된 스트림 얻기
            long time=System.currentTimeMillis();
            filename=time+"."+FileManager.getExtend(path,"/");
            fos=new FileOutputStream("C:\\koreaIT\\javaworkspace\\ShoppingApp\\data\\"+filename);
            
            int data=-1;
            while(true) {
                data=is.read();
                if(data==-1)break;
                fos.write(data);
            }
            JOptionPane.showMessageDialog(this.getAppMain(), "복사완료");
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
cs

 

step 14

1. 이제 상품을 DB에 등록하자

 

- ProductMain.java 추가/변경 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//상품등록
    public void regist() {
        PreparedStatement pstmt=null;
        
        String sql="insert into product(subcategory_id, product_name, price, brand, detail, filename)";
        sql+=" values(?,?,?,?,?,?)";
        int index= ch_sub.getSelectedIndex()-1;
        
        //얻어진 초이스 컴포넌트의 index를 이용하여, VO가 들어있는 ArrayList의 접근해보자!!
        Subcategory subcategory=subList.get(index);
        System.out.println("당신이 등록하려는 상품의 subcategory_id 는 "+ subcategory.getSubcategory_id());
        
        try {
            pstmt=this.getAppMain().getCon().prepareStatement(sql);
            //바인드 변수값 처리
            pstmt.setInt(1, subcategory.getSubcategory_id());//서브카테고리
            pstmt.setString(2, t_product_name.getText());//상품명
            pstmt.setInt(3, Integer.parseInt(t_price.getText()));//가격
            pstmt.setString(4, t_brand.getText());//브랜드
            pstmt.setString(5, t_detail.getText());//상세보기
            pstmt.setString(6, filename);//파일명
            
            //쿼리실행(DML)
            int result=pstmt.executeUpdate();
            if(result==1) {
                JOptionPane.showMessageDialog(this.getAppMain(), "상품 등록성공");
            }else {
                JOptionPane.showMessageDialog(this.getAppMain(), "상품 등록실패");
            }
            
            
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.getAppMain().release(pstmt);
        }
        
    }
cs

 

 

step 15

1. DB에 등록된 상품목록을 가져오자

 

<작업 결과물>

 

- ProductMain.java 추가/변경 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//상품 목록 가져오기
    public void getProductList() {
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        
        String sql="select product_id, sub_name, product_name, price, brand, detail,filename";
        sql+=" from subcategory s, product p";
        sql+=" where s.subcategory_id=p.subcategory_id";
        
        
        try {
            pstmt=this.getAppMain().getCon().prepareStatement(sql
                    , ResultSet.TYPE_SCROLL_SENSITIVE
                    , ResultSet.CONCUR_READ_ONLY);
            rs=pstmt.executeQuery();
            rs.last(); //커서를 마지막레코드로 보냄
            int total=rs.getRow();
            
            //JTable 이 참조하고 있는 records라는 이차원배열의 값을, rs를 이용하여 갱신해보자
            records=new String[total][columns.length];
            
            rs.beforeFirst(); //커서 위치 제자리로
            int index=0;
            while(rs.next()) {
                records[index][0]=Integer.toString(rs.getInt("product_id"));
                records[index][1]=rs.getString("sub_name");
                records[index][2]=rs.getString("product_name");
                records[index][3]=Integer.toString(rs.getInt("price"));
                records[index][4]=rs.getString("brand");
                records[index][5]=rs.getString("detail");
                records[index][6]=rs.getString("filename");
                index++;
            }
            table.updateUI();
            
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.getAppMain().release(pstmt, rs);
        }
    }
cs

 

step16

1. 액셀에 있는 자료를 DB에 저장하고 테이블에 나타나게 하자

  - java가 기본적으로 엑셀을 제어할 수 있는 api가 지원되지 않는다. 따라서 외부의 api 를 이용해야 한다
  - apache  개발한 라이브러리 이용해보자
  - appache.org : 무료 소프트웨어 진영을 이끌고 있는 단테!! POI jar

 

 

<작업 파일>

appache.org 에 있는 파일을 다운받아 lib 폴더에 저장한뒤 빌드인

<작업 결과물>

- ProductMain.java 추가/변경 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public void registByExcel() {
        //유저가 선택한 엑셀파일의 경로를 구한다
        String path=null;
        if(chooser.showOpenDialog(this.getAppMain())==JFileChooser.APPROVE_OPTION) {
            File file=chooser.getSelectedFile(); //파일정보얻기
            path=file.getAbsolutePath();
        }else {
            JOptionPane.showMessageDialog(this.getAppMain(), "엑셀파일을 선택해주세요");
            return//이하 라인을 못지나가게.. 함수 호출한 곳으로 실행부를 돌려보냄
        }
        
        //1) 엑셀에 접근부터 해야한다 (즉 빨대를 꽃아야한다)
        FileInputStream fis=null;
        XSSFWorkbook workbook=null;
        PreparedStatement  pstmt=null;
        try {
            fis=new FileInputStream(path);
            //이 스트림을 통해 내부데이터를 엑셀로 이해할수 있도록 해석
            //액셀파일을 처리하기 위한 객체 XSSFWorkbook
            workbook=new XSSFWorkbook(fis);
            
            XSSFSheet sheet=workbook.getSheetAt(0); //우리가 부여한 sheet 명을 이용하여 쉬트로 접근
            
            //쉬트객체를 이용해서 원하는 레코드에 접근해보자
            for (int i = 1; i < sheet.getLastRowNum(); i++) {
                XSSFRow row=sheet.getRow(i);
                
                int subcategory_id=0;
                String product_name=null;
                int price=0;
                String brand=null;
                String detail=null;
                String filename=null;
                
                
                //컬럼 수 만큼 반복
                for (int a = 0; a < row.getLastCellNum(); a++) {
                    XSSFCell cell=row.getCell(a);
                    //숫자일 경우, 문자열 경우 메서드가 틀리기 때문에 결국 자료형에 따라 조건으로 알맞는메서드 호출
                    if(a==0) {//subcategory_id
                        System.out.print(cell.getNumericCellValue());
                        subcategory_id=(int)cell.getNumericCellValue(); //double --> int
                    }else if(a==1) {
                        System.out.print(cell.getStringCellValue());
                        product_name=cell.getStringCellValue();
                    }else if(a==2) {
                        System.out.print(cell.getNumericCellValue());
                        price=(int)cell.getNumericCellValue();
                    }else if(a==3) {
                        System.out.print(cell.getStringCellValue());
                        brand=cell.getStringCellValue();
                    }else if(a==4) {
                        System.out.print(cell.getStringCellValue());
                        detail=cell.getStringCellValue();
                    }else if(a==5) {
                        System.out.print(cell.getStringCellValue());
                        filename=cell.getStringCellValue();
                    }
                }
                System.out.println();//줄바꿈
                String sql="insert into product(subcategory_id, product_name, price, brand, detail, filename)";
                sql+=" values(?,?,?,?,?,?)";
                
                Connection con=this.getAppMain().getCon();
//                con.setAutoCommit(false);//자동커밋하지마라~~ 커밋은 내가 주도해서 할거야
//                con.setAutoCommit(true);//매 DML 마다 커밋해라
                
                pstmt=null;
                pstmt=this.getAppMain().getCon().prepareStatement(sql);
                pstmt.setInt(1, subcategory_id);
                pstmt.setString(2, product_name);
                pstmt.setInt(3, price);
                pstmt.setString(4, brand);
                pstmt.setString(5, detail);
                pstmt.setString(6, filename);
                
                //쿼리실행
                pstmt.executeUpdate();
            }
 
            JOptionPane.showMessageDialog(this.getAppMain(), "등록완료");
            getProductList();
            
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(pstmt!=null) {
                this.getAppMain().release(pstmt);
            }
        }
    }
cs

 

 

반응형

'개발 > java' 카테고리의 다른 글

java 쇼핑몰 GUI(4)  (0) 2021.05.25
java 쇼핑몰 GUI(2)  (0) 2021.05.24
java 쇼핑몰 GUI (1)  (0) 2021.05.23
java Editplus / Eclipse에 .jar 추가 방법  (0) 2021.05.23
java 갤러리  (0) 2021.05.17

댓글