━━━━ ◇ ━━━━
Java/Java 프로젝트

Java 임금 계산기

시간당 5000원을 받는 일이 있다.

 

시간을 입력하면 임금을 계산하는 프로그램을 작성하되  8시간 이상일 때만 임금이 지급된다.

8시간 미만일 때는 시급의 반만 받는다.

 

 

 

입력

시간을 입력하세요 : 8

 

출력

임금은 40000원 입니다.

 

 

시간을 입력하세요 : 6

 

출력

임금은 15000원입니다.

 

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
import java.util.Scanner;
 
public class Wage_Calculate {
 
    public static void main(String[] args) {
        
        boolean flag = true;
        while(flag){
            Scanner scan = new Scanner(System.in);
            
            System.out.println("일한 시간을 입력하세요.");
            int inputTime = scan.nextInt();
            
            System.out.println("시급을 입력하세요.");
            int timeWages = scan.nextInt();
                    
            int totalWages =0;
            
            if(inputTime>=8){
                totalWages = inputTime * timeWages;
            }else{
                totalWages = (inputTime * timeWages) / 2;
            }
            
            System.out.println("당신이 받을 임금은 "+totalWages+"원 입니다.");
            System.out.println("===========================================");
            System.out.println("임금계산기를 종료하시겠습니까?");
            System.out.println("1.Yes, 2.No");
            int yesOrNo = scan.nextInt();
            
            while(true){
                if(yesOrNo == 1){
                    scan.close();
                    flag = false;
                    System.out.println("===========================================");
                    System.out.println("종료되었습니다.");
                    System.exit(0);
                    break;
                }else if(yesOrNo > 2){
                    System.out.println("===========================================");
                    System.out.println("1 또는 2를 입력하세요.");
                    System.out.println("임금계산기를 종료하시겠습니까?");
                    System.out.println("1.Yes, 2.No");
                    yesOrNo = scan.nextInt();
                }else{
                    System.out.println("===========================================");
                    break;
                }
            }
        }
        
        
 
    }
 
}
 

 

'Java > Java 프로젝트' 카테고리의 다른 글

Server and PieChart  (0) 2016.08.25
java swing 으로 music player 만들기  (0) 2016.08.10
COMMENT
━━━━ ◇ ━━━━
Java/JavaFx

JavaFx 04. 람다식으로 버튼 이벤트 표현하기

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
 
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
 
public class HelloWorld extends Application{
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        Button btn = new Button("Click me");
        // 종료 버튼을 추가한다.
        Button exit = new Button("Exit");
        // 람다식으로 이벤트를 처리해 본다.
        /*
         * new EventHandler<ActionEvent>() 가
         * e -> 로 
         * 축약된다.
         */
        exit.setOnAction(e -> {
            System.out.println("exit this App");
            System.exit(0);
        });
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("hello world");
                System.out.println("hello world");
                
            }
        });
        // 페인을 VBox 로 변경. Vertical 방향으로 배치된다.
        VBox root = new VBox();
        // addAll 메소드를 사용하면 한번에 여러 칠드런을 탑재할 수 있다.
        root.getChildren().addAll(btn, exit);
        Scene scene = new Scene(root, 500300);
        // 스테이지의 타이틀을 설정한다.
        primaryStage.setTitle("My title");
        primaryStage.setScene(scene);
        primaryStage.show();
        
    }
}
 
cs

 

 

 

COMMENT
━━━━ ◇ ━━━━
Java/JavaFx

JavaFx 03. Application 만들기

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
 
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class HelloWorld extends Application{
    public static void main(String[] args) {
        launch(args); //실행
    }
    //Application 을 상속 받은 다음 오버라이드 한다.
    @Override
    public void start(Stage primaryStage) throws Exception {
        // 버튼 생성. 임포트 주의할것
        Button btn = new Button("Click me"); 
        // 버튼 이벤트
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("hello world");
                
            }
        }); 
        // 기본 페인 설정. 도화지 같은 개념 
        StackPane root = new StackPane(); 
        // 기본 페인에 버튼을 추가
        root.getChildren().add(btn); 
        // 화면(scene) 설정. 기본페인을 보여주는데 크기는 500px, 300px 이다.
        Scene scene = new Scene(root, 500300); 
        // 스테이지의 화면을 설정한다.
        primaryStage.setScene(scene);
        // 스테이지를 보여준다.
        primaryStage.show();
        
    }
}
 
cs

 

실행 사진

 

 

COMMENT
━━━━ ◇ ━━━━
Java/Java 프로젝트

java swing 으로 music player 만들기

1. 개요

- 강사님이 자바 스윙으로 뮤직 플레이어를 만들어보라고 하셨다.

- 사용해야할 주요기능은 DB 연동, Image, Audio 등이다.

 

2. 자료구조

 

3. 소스코드

3.1 Main

1
2
3
4
5
6
7
8
9
10
11
12
13
package Main;
 
import Frame.MainFrame;
 
public class Main {
    
    public static void main(String[] args) {
        new MainFrame();
 
    }
 
}
 
cs

 

3.2 MainFrame

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package Frame;
 
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
 
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
 
import Center.FirstPanel;
import Center.InsertPanel;
import Center.ShowPanel;
import Dialog.DeleteConfirmDialog;
import Dialog.ListPlzDialog;
import Dialog.ListPlzDialog2;
import Dialog.OneChkPlzDialog;
import Dialog.OneChkPlzDialog2;
import Head.CategoriPanel;
import Head.TitlePanel;
 
public class MainFrame extends JFrame implements ActionListenerMouseListener{
    
    private JPanel northPanel;
    private JPanel centerPanel;
    private TitlePanel tp;
    private CategoriPanel cp;
    private FirstPanel fp;
    private InsertPanel ip;
    private ShowPanel sp;
        
    public MainFrame() {
        setTitle("메인화면");
        setSize(19001000);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                
        //Head
        northPanel = new JPanel();
        northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.Y_AXIS));
        
        //Head - 메인화면으로
        tp = new TitlePanel();
        tp.addMouseListener(this);
        northPanel.add(tp);
        
        //Head - 음악 목록 보기
        cp = new CategoriPanel();
        cp.getShowAlbumListBtn().addActionListener(this);
        
        //Head - 음악 추가
        cp.getInsertAlbumBtn().addActionListener(this);
        
        //Head - 음악 수정
        cp.getUpdateAlbumBtn().addActionListener(this);
        
        //Head - 음악 삭제
        cp.getDeleteAlbumBtn().addActionListener(this);
        
        //Head - 음악 듣기
        cp.getStartMusicBtn().addActionListener(this);
        northPanel.add(cp);
        add(northPanel, BorderLayout.NORTH);
        
        //Center
        centerPanel = new JPanel();
            
        //Center - 첫패널
        fp = new FirstPanel();
        fp.setVisible(true);
        centerPanel.add(fp);
        
        //Center - 음악 목록 보기 패널
        sp = new ShowPanel();
        sp.setVisible(false);
        centerPanel.add(sp);
        
        //Center - 음악 추가 패널
        ip = new InsertPanel();
        ip.setVisible(false);
        centerPanel.add(ip);
        
        //Center - scrollpane
        JScrollPane scroll = new JScrollPane(centerPanel);
        //scroll.setSize(1900, 700);
        //scroll.setLocation(0, 50);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setViewportView(centerPanel);
        
        add(scroll, BorderLayout.CENTER);
                
        //add(centerPanel, BorderLayout.CENTER);
        
        
        setVisible(true);
    }
 
    //Head btn events
    @Override
    public void actionPerformed(ActionEvent e) {
        //음악 목록 보기 버튼을 눌렸을 때
        if(e.getSource()==cp.getShowAlbumListBtn()){
            sp.showMethod();
            //sp.repaint();
            fp.setVisible(false);
            ip.setVisible(false);
            sp.setVisible(true);
            
        }
        //음악 삽입 버튼을 눌렸을 때
            if(e.getSource()==cp.getInsertAlbumBtn()){
                fp.setVisible(false);
                sp.setVisible(false);
                ip.setVisible(true);
            }
        //음악 수정 버튼을 눌렸을 때
        if(e.getSource()==cp.getUpdateAlbumBtn()){
            //음악 수정은 음악 목록 보기에서 체크 되어 있을 때만 가능
            //음악 목록 보기가 활성화 되어 있는지 확인
            if(sp.isVisible()){
                if(sp.getChk()==1){ // 음악이 1개만 선택 되어 있다면?
                    UpdateFrame uf = new UpdateFrame();                    
                    fp.setVisible(false);
                    ip.setVisible(false);
                    sp.setVisible(false);
                }else// 음악이 선택되지 않았거나 여러개 선택되었다면?
                    new Dialog(new OneChkPlzDialog());
                    fp.setVisible(false);
                    ip.setVisible(false);
                    sp.setVisible(true);
                }
            }else//음악 목록 보기가 활성화 되어 있지 않다면?
                new Dialog(new ListPlzDialog());
                fp.setVisible(false);
                ip.setVisible(false);
                sp.setVisible(true);
            }
            
        }
        //삭제 버튼을 눌렸을 때
        if(e.getSource() == cp.getDeleteAlbumBtn()){
            //음악 삭제도 음악 목록 보기에서 체크 되어 있을 때만 가능
            //음악 목록 보기가 활성화 되어 있는지 확인
            if(sp.isVisible()){
                if(sp.getChk()==0){ // 음악이 선택 되어 있지않다면?
                    new Dialog(new OneChkPlzDialog2());
                    fp.setVisible(false);
                    ip.setVisible(false);
                    sp.setVisible(true);
                }else
                    DeleteConfirmDialog dcd = new DeleteConfirmDialog();
                    fp.setVisible(false);
                    ip.setVisible(false);
                    sp.setVisible(true);
                }                
            }else//음악 목록 보기가 활성화 되어 있지 않다면?
                new Dialog(new ListPlzDialog());
                fp.setVisible(false);
                ip.setVisible(false);
                sp.setVisible(true);
            }
        }
        //음악 듣기 버튼을 눌렸을 때
        if(e.getSource() == cp.getStartMusicBtn()){
            //음악 듣기도 음악 목록 보기에서 체크되어 있을 때만 가능
            //음악 목록 보기가 활성화 되어 있는지 확인
            if(sp.isVisible()){
                if(sp.getChk()==1){ // 음악이 1개만 선택 되어 있다면?
                    MusicFrame mf = new MusicFrame();            
                    fp.setVisible(false);
                    ip.setVisible(false);
                    sp.setVisible(true);
                }else// 음악이 선택되지 않았거나 여러개 선택되었다면?
                    new Dialog(new OneChkPlzDialog());
                    fp.setVisible(false);
                    ip.setVisible(false);
                    sp.setVisible(true);
                }
            }else//음악 목록 보기가 활성화 되어 있지 않다면?
                new Dialog(new ListPlzDialog2());
                fp.setVisible(false);
                ip.setVisible(false);
                sp.setVisible(true);
            }
            
            
        }
    }
 
    @Override
    public void mouseClicked(MouseEvent e) {
        if(e.getSource()==tp){
            sp.setVisible(false);
            ip.setVisible(false);
            fp.setVisible(true);
        }
        
    }
 
    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }
 
    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }
 
    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }
 
    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }
 
    
    
    
}
 
cs

 

3.3 CategoriPanel

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
package Head;
 
import java.awt.Color;
 
import javax.swing.JButton;
import javax.swing.JPanel;
 
public class CategoriPanel extends JPanel {
    private JButton showAlbumListBtn;
    private JButton insertAlbumBtn;
    private JButton updateAlbumBtn;
    private JButton deleteAlbumBtn;
    private JButton startMusicBtn;
    
    public CategoriPanel() {
        setBackground(new Color(171,242,0));
        setSize(190050);
        showAlbumListBtn = new JButton("음악 목록 보기");
        add(showAlbumListBtn);
        
        insertAlbumBtn = new JButton("음악 추가");
        add(insertAlbumBtn);
        
        updateAlbumBtn = new JButton("음악 수정");
        add(updateAlbumBtn);
        
        deleteAlbumBtn = new JButton("음악 삭제");
        add(deleteAlbumBtn);
        
        startMusicBtn = new JButton("음악 듣기");
        add(startMusicBtn);
    }
 
    public JButton getShowAlbumListBtn() {
        return showAlbumListBtn;
    }
 
    public JButton getInsertAlbumBtn() {
        return insertAlbumBtn;
    }
 
    public JButton getUpdateAlbumBtn() {
        return updateAlbumBtn;
    }
 
    public JButton getDeleteAlbumBtn() {
        return deleteAlbumBtn;
    }
    
    public JButton getStartMusicBtn(){
        return startMusicBtn;
    }
    
}
 
cs

 

3.4 TitlePanel

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
package Head;
 
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
 
import javax.imageio.ImageIO;
import javax.swing.JPanel;
 
public class TitlePanel extends JPanel {
    private BufferedImage image;
    public TitlePanel(){
        try {
            File file = new File("C:\\Temp\\titlePic.png");
            image = ImageIO.read(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void paint(Graphics g) {
        g.drawImage(image, 00null);
    }
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(1900200);
        
    }
    public BufferedImage getImage() {
        return image;
    }
    
}
 
cs

 

3.5 Album

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
package DB;
 
import java.io.InputStream;
 
public class Album {
 
    private int id;
    private String name;
    private String date;
    private String singer;
    private String title;
    private String genre;
    private String picName;
    private InputStream picture;
    private int picLength;
    private String musicName;
    private InputStream music;
    private int musicLength;
    
    public String getMusicName() {
        return musicName;
    }
    public void setMusicName(String musicName) {
        this.musicName = musicName;
    }
    public InputStream getMusic() {
        return music;
    }
    public void setMusic(InputStream music) {
        this.music = music;
    }
    public int getMusicLength() {
        return musicLength;
    }
    public void setMusicLength(int musicLength) {
        this.musicLength = musicLength;
    }
    public String getPicName() {
        return picName;
    }
    public void setPicName(String picName) {
        this.picName = picName;
    }
    public int getPicLength() {
        return picLength;
    }
    public void setPicLength(int picLength) {
        this.picLength = picLength;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getSinger() {
        return singer;
    }
    public void setSinger(String singer) {
        this.singer = singer;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getGenre() {
        return genre;
    }
    public void setGenre(String genre) {
        this.genre = genre;
    }
    public InputStream getPicture() {
        return picture;
    }
    public void setPicture(InputStream picture) {
        this.picture = picture;
    }
    
    
    
}
 
cs

 

3.6 DBConnector

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package DB;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
 
public class DBConnector {
 
    private Connection con = null;
    private String driverName = "com.mysql.jdbc.Driver";
    private String dbURL = "jdbc:mysql://192.168.0.20:3306/melon";
    private String dbUser = "IT";
    private String dbPassword = "1234";
    private Statement stmt;
    private PreparedStatement pstmt;
    private ResultSet rs;
    
    private ArrayList<Album> data = new ArrayList<>();
        
    public DBConnector() {
        try {
            Class.forName(driverName);
            con = DriverManager.getConnection(dbURL, dbUser, dbPassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //음악 추가
    public void insertDB(String name, String date, String singer, String title, String genre, InputStream picture, String picName, int picLength, InputStream music, String musicName, int musicLength){
        try {
            String sql = "insert into album (name, date, singer, title, genre, picname, musicname)"
                    + "values (?, ?, ?, ?, ?, ?, ?)";                    
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, date);
            pstmt.setString(3, singer);
            pstmt.setString(4, title);
            pstmt.setString(5, genre);
            pstmt.setString(6, picName);
            pstmt.setString(7, musicName);
            pstmt.executeUpdate();
            
            sql = "insert into pic (picname, picture, piclength) values (?, ?, ?)";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, picName);
            pstmt.setBinaryStream(2, picture, picLength);
            pstmt.setInt(3, picLength);
            pstmt.executeUpdate();
            
            sql = "insert into music (musicname, music, musiclength) values (?, ?, ?)";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, musicName);
            pstmt.setBinaryStream(2, music, musicLength);
            pstmt.setInt(3, musicLength);
            pstmt.executeUpdate();
            
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(pstmt!=null){
                    pstmt.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    
    //음악 목록 보기
    public ArrayList<Album> showDB(){
        try {
            String sql = "select a.*, p.picture, p.piclength, m.music, m.musiclength from album a join pic p join music m on a.picname = p.picname and a.musicname = m.musicname";
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                Album ab = new Album();
                ab.setId(rs.getInt(1));
                ab.setName(rs.getString(2));
                ab.setDate(rs.getString(3));
                ab.setSinger(rs.getString(4));
                ab.setTitle(rs.getString(5));
                ab.setGenre(rs.getString(6));
                ab.setPicName(rs.getString(7));
                ab.setMusicName(rs.getString(8));
                ab.setPicture(rs.getBinaryStream(9));
                ab.setPicLength(rs.getInt(10));
                ab.setMusic(rs.getBinaryStream(11));
                ab.setMusicLength(rs.getInt(12));
                data.add(ab);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs!=null){
                    rs.close();
                }
                if(stmt!=null){
                    stmt.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }
    //음악 검색
    public Album selectDB(int id){
        Album ab = new Album(); 
        try {
            String sql = "select a.*, p.picture, p.piclength, m.music, m.musiclength from album a join pic p join music m on a.picname = p.picname and a.musicname = m.musicname and id="+id;
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            
            while(rs.next()){
                ab.setId(rs.getInt(1));
                ab.setName(rs.getString(2));
                ab.setDate(rs.getString(3));
                ab.setSinger(rs.getString(4));
                ab.setTitle(rs.getString(5));
                ab.setGenre(rs.getString(6));
                ab.setPicName(rs.getString(7));
                ab.setMusicName(rs.getString(8));
                ab.setPicture(rs.getBinaryStream(9));
                ab.setPicLength(rs.getInt(10));
                ab.setMusic(rs.getBinaryStream(11));
                ab.setMusicLength(rs.getInt(12));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs!=null){
                    rs.close();
                }
                if(stmt!=null){
                    stmt.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ab;
    }
    //음악 수정
    public void updateDB(int id, String name, String date, String singer, String title, String genre, String picName, InputStream picture, int lengthString musicName, InputStream music, int musicLength){
        try {
            String sql = "update album set name=?, date=?, singer=?, title=?, genre=?, picname=?, musicname=? where id=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, date);
            pstmt.setString(3, singer);
            pstmt.setString(4, title);
            pstmt.setString(5, genre);
            pstmt.setString(6, picName);
            pstmt.setString(7, musicName);
            pstmt.setInt(8, id);
            pstmt.executeUpdate();
            
            sql = "update pic set picture=?, piclength=? where picname=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setBinaryStream(1, picture, length);
            pstmt.setInt(2length);
            pstmt.setString(3, picName);
            pstmt.executeUpdate();
            
            sql = "update music set music=?, musiclength=? where musicname=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setBinaryStream(1, music, musicLength);
            pstmt.setInt(2, musicLength);
            pstmt.setString(3, musicName);
            pstmt.executeUpdate();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(pstmt!=null){
                    pstmt.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }        
    }
    //음악 삭제
    public void deleteDB(int id){
        try {
            String picName = null;
            String sql = "select picname from album where id="+id;
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            if(rs.next()){
                picName = rs.getString(1);
            }
            
            String musicName = null;
            sql = "select musicname from album where id="+id;
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            if(rs.next()){
                musicName = rs.getString(1);
            }    
            
            sql = "delete from album where id=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
            
            sql = "delete from pic where picname=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, picName);
            pstmt.executeUpdate();
            
            sql = "delete from music where musicname=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, musicName);
            pstmt.executeUpdate();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(pstmt!=null){
                    pstmt.close();
                }
                if(rs!=null){
                    rs.close();
                }
                if(stmt!=null){
                    stmt.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
 
cs

 

3.7 FirstPanel

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
package Center;
 
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 
import javax.imageio.ImageIO;
import javax.swing.JPanel;
 
public class FirstPanel extends JPanel {
 
    BufferedImage image;
    
    public FirstPanel() {
        
        try {
            image = ImageIO.read(new File("C:\\Temp\\main.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void paint(Graphics g) {
        g.drawImage(image, 00null);        
    }
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(1900,750);        
    }
    
}
 
cs

 

3.8 ShowPanel

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package Center;
 
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
 
import javax.imageio.ImageIO;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
import DB.Album;
import DB.DBConnector;
 
public class ShowPanel extends JPanel{
 
    //전역 변수 설정
    private JPanel topPanel; // 카테고리 라벨들을 붙일 패널
    private JLabel[] topLbl; // 카테고리 라벨들
    
    private ArrayList<Album> data;
    private DBConnector dbc; 
    private JPanel centerPanel; // rowPanel 들을 붙일 패널
    
    
    private int chkCount = 0// 체크박스를 선택한 개수를 담을 변수
    private JCheckBox chk; // 체크박스 
    private int[] ids;
    
    private static int chkID;
    private static LinkedList<Integer> chkIDs = new LinkedList<>();
    
    public ShowPanel() {
        setLayout(null);
        setVisible(true);
        
        //topPanel 영역 ------------------------------------------
        topPanel = new JPanel();
        topPanel.setBounds(00190050);
        topPanel.setLayout(null);
        add(topPanel);
        
        topLbl = new JLabel[7];
        String[] topLblText = {"선택""앨범사진""제목""가수명""발매일",
                "장르""앨범명"};
        Font font = new Font("D2Coding", Font.BOLD, 20);
        for (int i = 0; i < topLbl.length; i++) {
            topLbl[i] = new JLabel();
            topLbl[i].setText(topLblText[i]);
            topLbl[i].setHorizontalAlignment((int)CENTER_ALIGNMENT);
            topLbl[i].setFont(font);
            topLbl[i].setBounds(i*270027050);
            topPanel.add(topLbl[i]);
        }
        
        //centerPanel 영역 ---------------------------------------------
        data = new ArrayList<>();
        dbc = new DBConnector();
        centerPanel = new JPanel();
        centerPanel.setBounds(0501900700);
        //centerPanel.setLayout(new GridLayout(data.size(), 1, 0, 0));
        centerPanel.setLayout(null);
        add(centerPanel);
                
    }
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(1900750);
    }
    //이미지를 그리는 inner class
    class DrawImgPanel extends JPanel{
        BufferedImage is;
        public DrawImgPanel(BufferedImage is) {
            this.is = is;
            
        }
        
        @Override
        public void paint(Graphics g) {
            g.drawImage(is, 700120100null);
        }
        
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(270100);
        }
    }
    //show method - db에서 음악 목록을 불러와서 뿌려준다.
    public void showMethod(){
        centerPanel.removeAll();
        data.clear();
        data = dbc.showDB();
        JPanel[] rowPanel = new JPanel[data.size()];
        chk = new JCheckBox();
        ids = new int[data.size()];
        for (int i = 0; i < data.size(); i++) {
            rowPanel[i] = new JPanel();
            rowPanel[i].setLayout(null);
            
            Integer id = data.get(i).getId();
                        
            chk = new JCheckBox();    
            chk.setBounds(120255050);
            chk.addItemListener(new ItemListener() {
                
                @Override
                public void itemStateChanged(ItemEvent e) {
                    if(e.getStateChange() == e.SELECTED){
                        chkCount++;
                        chkIDs.add(id);
                        System.out.println(chkIDs);
                        
                    }else if(e.getStateChange() == e.DESELECTED){
                        chkCount--;
                        chkIDs.remove(id);
                        System.out.println(chkIDs);
                    }                    
                    
                }
            });
            InputStream picture = data.get(i).getPicture();
            DrawImgPanel imgPanel = null;
            try {
                imgPanel = new DrawImgPanel(ImageIO.read(picture));
                imgPanel.setBounds(2700270100);                
            } catch (IOException e) {}
                        
            String name = data.get(i).getName();
            String singer = data.get(i).getSinger();
            String date = data.get(i).getDate();
            String genre = data.get(i).getGenre();
            String title = data.get(i).getTitle();
            
            JLabel[] contentsLbl = new JLabel[5];
            for (int j = 0; j < contentsLbl.length; j++) {
                contentsLbl[j] = new JLabel();
            }
            contentsLbl[0].setText(name);
            contentsLbl[0].setBounds(5400270100);
            contentsLbl[0].setHorizontalAlignment((int)CENTER_ALIGNMENT);
            contentsLbl[1].setText(singer);
            contentsLbl[1].setBounds(8100270100);
            contentsLbl[1].setHorizontalAlignment((int)CENTER_ALIGNMENT);
            contentsLbl[2].setText(date);
            contentsLbl[2].setBounds(10800270100);
            contentsLbl[2].setHorizontalAlignment((int)CENTER_ALIGNMENT);
            contentsLbl[3].setText(genre);
            contentsLbl[3].setBounds(13500270100);
            contentsLbl[3].setHorizontalAlignment((int)CENTER_ALIGNMENT);
            contentsLbl[4].setText(title);
            contentsLbl[4].setBounds(16200270100);
            contentsLbl[4].setHorizontalAlignment((int)CENTER_ALIGNMENT);
                        
            rowPanel[i].add(chk);
            rowPanel[i].add(imgPanel);
            rowPanel[i].add(contentsLbl[0]);
            rowPanel[i].add(contentsLbl[1]);
            rowPanel[i].add(contentsLbl[2]);
            rowPanel[i].add(contentsLbl[3]);
            rowPanel[i].add(contentsLbl[4]);
            
            rowPanel[i].setBounds(0, i*1101900100);
 
            centerPanel.add(rowPanel[i]);
        }
        
    }    
    
    public int getChk(){
        return chkCount;
    }
    
    public int getChkID(){
        if(chkIDs.size()==1){
            chkID = chkIDs.get(0);
        }
        return chkID;
    }
    
    public LinkedList<Integer> getChkIDs(){
        return chkIDs;
    }
    
}
 
cs

 

3.9 InsertPanel

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package Center;
 
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
 
import DB.DBConnector;
import Dialog.SuccessDialog;
 
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSeparator;
import java.awt.Color;
import java.awt.Dialog;
 
public class InsertPanel extends JPanel implements ActionListener{
    
    private JTextField tf1, tf2, tf3, tf4, tf5;
    private JLabel lb1, lb2, lb3, lb4, lb5, lb6, lb7, lb8, lb9;
    private JButton btn1, btn2, btn3;
    private JFrame jf;
    private FileDialog fd1;
    private InputStream fis, musicFis;
    private String picName, musicName;
    private int picLength, musicLength;
    public InsertPanel() {
        setLayout(null);
        
        lb1 = new JLabel("곡명");
        lb1.setBounds(34346218);
        add(lb1);
                
        lb2 = new JLabel("발매일");
        lb2.setBounds(34646218);
        add(lb2);
                
        lb3 = new JLabel("가수");
        lb3.setBounds(34946218);
        add(lb3);
        
        lb4 = new JLabel("앨범명");
        lb4.setBounds(341246218);
        add(lb4);
        
        lb5 = new JLabel("장르");
        lb5.setBounds(341546218);
        add(lb5);
        
        tf1 = new JTextField();
        tf1.setBounds(1063133024);
        add(tf1);
        tf1.setColumns(10);
        
        tf2 = new JTextField();
        tf2.setBounds(1066133024);
        add(tf2);
        tf2.setColumns(10);
        
        tf3 = new JTextField();
        tf3.setBounds(1069133024);
        add(tf3);
        tf3.setColumns(10);
        
        tf4 = new JTextField();
        tf4.setBounds(10612133024);
        add(tf4);
        tf4.setColumns(10);
        
        tf5 = new JTextField();
        tf5.setBounds(10615133024);
        add(tf5);
        tf5.setColumns(10);
        
        lb6 = new JLabel("사진");
        lb6.setBounds(341886218);
        add(lb6);
        
        lb7 = new JLabel("");
        lb7.setBounds(10618820024);
        add(lb7);
        
        lb8 = new JLabel("음악");
        lb8.setBounds(342226218);
        add(lb8);
        
        lb9 = new JLabel("");
        lb9.setBounds(10622220024);
        add(lb9);
        
        btn1 = new JButton("사진넣기");
        btn1.setBounds(9327210539);
        btn1.addActionListener(this);
        add(btn1);
        
        btn2 = new JButton("저장");
        btn2.setBounds(33127210539);
        btn2.addActionListener(this);
        add(btn2);
        
        btn3 = new JButton("음악넣기");
        btn3.setBounds(21227210539);
        btn3.addActionListener(this);
        add(btn3);
        
        JSeparator separator = new JSeparator();
        separator.setForeground(Color.BLACK);
        separator.setBounds(342574002);
        add(separator);
    }
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(600500);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //사진 넣기
        if(e.getSource() == btn1){
            try {
                jf = new JFrame();
                jf.setSize(300300);
                jf.setDefaultCloseOperation(jf.DISPOSE_ON_CLOSE);
                
                fd1 = new FileDialog(jf, "사진을 선택하시오.", FileDialog.LOAD);
                fd1.setVisible(true);
                String fileDir = fd1.getDirectory(); // 선택한 파일 경로가져옴
                String fileName = fd1.getFile(); // 파일이름,확장자
                
                File file = new File(fileDir + fileName);
                fis = new FileInputStream(file);
                picName = fileDir + fileName;
                picLength = (int) file.length();
                
                lb7.setText(fileDir + "\\" + fileName);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //저장
        if(e.getSource() == btn2){
            String name = tf1.getText().toString();
            String date = tf2.getText().toString();
            String singer = tf3.getText().toString();
            String title = tf4.getText().toString();
            String genre = tf5.getText().toString();
            DBConnector dbc = new DBConnector();
            dbc.insertDB(name, date, singer, title, genre, fis, picName, picLength, musicFis, musicName, musicLength);
            
            SuccessDialog sd = new SuccessDialog();
            Dialog dl = new Dialog(sd);
            
            tf1.setText("");
            tf2.setText("");
            tf3.setText("");
            tf4.setText("");
            tf5.setText("");
            lb7.setText("");
            lb9.setText("");
            
        }
        //음악 넣기
        if(e.getSource() == btn3){
            try {
                jf = new JFrame();
                jf.setSize(300300);
                jf.setDefaultCloseOperation(jf.DISPOSE_ON_CLOSE);
                
                fd1 = new FileDialog(jf, "음악을 선택하시오.", FileDialog.LOAD);
                fd1.setVisible(true);
                String fileDir = fd1.getDirectory(); // 선택한 파일 경로가져옴
                String fileName = fd1.getFile(); // 파일이름,확장자
                
                File file = new File(fileDir + fileName);
                musicFis = new FileInputStream(file);
                musicName = fileDir + fileName;
                musicLength = (int) file.length();
                
                lb9.setText(fileDir + "\\" + fileName);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
 
cs

 

3.10 UpdateFrame

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package Frame;
 
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
 
import Center.ShowPanel;
import DB.Album;
import DB.DBConnector;
import Dialog.SuccessDialog;
 
public class UpdateFrame extends JFrame {
 
    private ShowPanel sp;
    private int id;
    private DBConnector dbc;
    private Album ab;
    public UpdateFrame() {
        setBounds(700300500500);
        setDefaultCloseOperation(UpdateFrame.DISPOSE_ON_CLOSE);
        
        sp = new ShowPanel();
        id = sp.getChkID();
        dbc = new DBConnector();
        ab = new Album();
        ab = dbc.selectDB(id);
        
        UpdatePanel up = new UpdatePanel();
        add(up);
        setVisible(true);
    }
    class UpdatePanel extends JPanel implements ActionListener {
 
        private ImgPanel imgPanel;
        private JTextField tf1, tf2, tf3, tf4, tf5;
        private JLabel lb1, lb2, lb3, lb4, lb5, lb6, lb7;
        private JButton btn1, btn2, btn3;
        private String name ;
        private String date ;
        private String singer ;
        private String title ;
        private String genre ;
        private String picName;
        private InputStream picture = null;
        private int picLength;
        private InputStream fis = null;
        private int length = 0;
        private InputStream musicFis = null;
        private String musicName;
        private InputStream music = null;
        private int musicLength = 0;
        
                
        public UpdatePanel() {
            setSize(500500);
            setLayout(null);
            
            name = ab.getName();
            date = ab.getDate();
            singer = ab.getSinger();
            title = ab.getTitle();
            genre = ab.getGenre();
            picName = ab.getPicName();
            picture = ab.getPicture();
            picLength = ab.getPicLength();
            musicName = ab.getMusicName();
            music = ab.getMusic();
            musicLength = ab.getMusicLength();
            
            try {
                imgPanel = new ImgPanel(ImageIO.read(picture));
            } catch (IOException e) {
                e.printStackTrace();
            }
            imgPanel.setBounds(1010300300);
            add(imgPanel);
                        
            //곡명
            lb1 = new JLabel("곡명");
            lb1.setBounds(3251015025);
            add(lb1);
            
            tf1 = new JTextField();
            tf1.setBounds(3253515025);
            tf1.setText(name);
            add(tf1);
            
            
            //발매일
            lb2 = new JLabel("발매일");
            lb2.setBounds(3256015025);
            add(lb2);
            
            tf2 = new JTextField();
            tf2.setBounds(3258515025);
            tf2.setText(date);
            add(tf2);
            
            
            //가수
            lb3 = new JLabel("가수");
            lb3.setBounds(32511015025);
            add(lb3);
            
            tf3 = new JTextField();
            tf3.setBounds(32513515025);
            tf3.setText(singer);
            add(tf3);
            
            //앨범명
            lb4 = new JLabel("앨범명");
            lb4.setBounds(32516015025);
            add(lb4);
            
            tf4 = new JTextField();
            tf4.setBounds(32518515025);
            tf4.setText(title);
            add(tf4);
            
            //장르
            lb5 = new JLabel("장르");
            lb5.setBounds(32521015025);
            add(lb5);
            
            tf5 = new JTextField();
            tf5.setBounds(32523515025);
            tf5.setText(genre);
            add(tf5);
            
            //음악
            lb6 = new JLabel("음악");
            lb6.setBounds(32526015025);
            add(lb6);
            
            lb7 = new JLabel("");
            lb7.setBounds(32528515025);
            lb7.setText(musicName);
            add(lb7);
            
            //분리선
            JSeparator separator = new JSeparator();
            separator.setBounds(203254505);
            add(separator);
            
            //저장 버튼
            btn1 = new JButton("저장");
            btn1.setBounds(32037012030);
            btn1.addActionListener(this);
            add(btn1);
            
            //사진 넣기 버튼
            btn2 = new JButton("사진넣기");
            btn2.setBounds(6037012030);
            btn2.addActionListener(this);
            add(btn2);
            
            //음악 넣기 버튼
            btn3 = new JButton("음악넣기");
            btn3.setBounds(19037012030);
            btn3.addActionListener(this);
            add(btn3);
            
        }
        class ImgPanel extends JPanel{
            BufferedImage is;
            public ImgPanel(BufferedImage is) {
                this.is = is;
                
            }
            
            public void imgChange(BufferedImage cImg){
                is = cImg;
            }
            
            @Override
            public void paint(Graphics g) {
                g.drawImage(is, 00300300null);
            }
            
 
            
            @Override
            public Dimension getPreferredSize() {
                
                return new Dimension(120120);
            }
        }
        //버튼 이벤트
        @Override
        public void actionPerformed(ActionEvent e) {
            //저장
            if(e.getSource() == btn1){
                name = tf1.getText().toString();
                date = tf2.getText().toString();
                singer = tf3.getText().toString();
                title = tf4.getText().toString();
                genre = tf5.getText().toString();
                if(fis != null){
                    picture = fis;
                }else{
                    File file = new File(picName);
                    try {
                        picture = new FileInputStream(file);
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    }
                }
                if(length == 0){
                    length = picLength;
                }
                
                dbc.updateDB(id, name, date, singer, title, genre, picName, picture, length, musicName, music, musicLength);
                new Dialog(new SuccessDialog());
                dispose();
            }
            //사진넣기
            if(e.getSource() == btn2){
                try {
                    JFrame jf = new JFrame();
                    jf.setSize(300300);
                    jf.setDefaultCloseOperation(jf.DISPOSE_ON_CLOSE);
                    
                    FileDialog fd1 = new FileDialog(jf, "사진을 선택하시오.", FileDialog.LOAD);
                    fd1.setVisible(true);
                    
                    String fileDir = fd1.getDirectory(); // 선택한 파일 경로가져옴
                    String fileName = fd1.getFile(); // 파일이름,확장자
                    
                    File file = new File(fileDir + fileName);
                    fis = new FileInputStream(file);
                    picName = fileDir + fileName;
                    length = (int) file.length();
                    
                    System.out.println(fileDir + fileName);
                    
                    /*remove(imgPanel);
                    imgPanel = new ImgPanel(ImageIO.read(file));
                    imgPanel.setBounds(10, 10, 300, 300);
                    add(imgPanel);
                    repaint();*/
                    
                    imgPanel.imgChange(ImageIO.read(file));
                    repaint();
                                                            
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            //음악 넣기
            if(e.getSource() == btn3){
                try {
                    JFrame jf = new JFrame();
                    jf.setSize(300300);
                    jf.setDefaultCloseOperation(jf.DISPOSE_ON_CLOSE);
                    
                    FileDialog fd1 = new FileDialog(jf, "음악을 선택하시오.", FileDialog.LOAD);
                    fd1.setVisible(true);
                    
                    String fileDir = fd1.getDirectory(); // 선택한 파일 경로가져옴
                    String fileName = fd1.getFile(); // 파일이름,확장자
                    
                    File file = new File(fileDir + fileName);
                    musicFis = new FileInputStream(file);
                    musicName = fileDir + fileName;
                    musicLength = (int) file.length();
                    
                    lb7.setText(musicName);
                                                                                                    
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }
    
}
 
cs

 

3.11 MusicFrame

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package Frame;
 
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
 
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
 
import Center.ShowPanel;
import DB.Album;
import DB.DBConnector;
import Frame.UpdateFrame.UpdatePanel.ImgPanel;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
 
public class MusicFrame extends JFrame{
 
    private ShowPanel sp;
    private int id;
    private DBConnector dbc;
    private Album ab;
    
    
    
    public MusicFrame() {
        setTitle("뮤직 플레이어");
        setSize(500500);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(MusicFrame.DISPOSE_ON_CLOSE);
        
        sp = new ShowPanel();
        id = sp.getChkID();
        dbc = new DBConnector();
        ab = new Album();
        ab = dbc.selectDB(id);
        
        MusicPlayerPanel mpp = new MusicPlayerPanel();
        add(mpp);
                
        setVisible(true);
        
        
        
    }
    class MusicPlayerPanel extends JPanel implements ActionListener{
 
        private File musicFile;
        private InputStream isMusic;
        private AudioStream asMusic;
        private AudioPlayer apMusic;
        private JButton btnStart, btnChange, btnStop;
        private JLabel lblTitle, lblSinger;
        private String name, singer;
        private InputStream picture = null;
        private InputStream music = null;
        private ImgPanel2 imgPanel;
        
        public MusicPlayerPanel() {
            setSize(500,500);
            getContentPane().setLayout(null);
            
            name = ab.getName();
            singer = ab.getSinger();
            picture = ab.getPicture();
            music = ab.getMusic();
            
            btnStart = new JButton("음악시작");
            btnStart.setBounds(1040015030);
            btnStart.addActionListener(this);
            getContentPane().add(btnStart);
            
            btnChange = new JButton("음악변경");
            btnChange.setBounds(16840015030);
            btnChange.addActionListener(this);
            getContentPane().add(btnChange);
            
            btnStop = new JButton("음악정지");
            btnStop.setBounds(32540015030);
            btnStop.addActionListener(this);
            getContentPane().add(btnStop);
            
            try {
                imgPanel = new ImgPanel2(ImageIO.read(picture));
            } catch (Exception e) {
                e.printStackTrace();
            }
            imgPanel.setBounds(8510300300);
            getContentPane().add(imgPanel);
            
            lblTitle = new JLabel("\uC81C\uBAA9");
            lblTitle.setBounds(1032046525);
            lblTitle.setText(name);
            lblTitle.setHorizontalAlignment((int)CENTER_ALIGNMENT);
            getContentPane().add(lblTitle);
            
            lblSinger = new JLabel("\uAC00\uC218");
            lblSinger.setBounds(1035046525);
            lblSinger.setText(singer);
            lblSinger.setHorizontalAlignment((int)CENTER_ALIGNMENT);
            getContentPane().add(lblSinger);
                        
            apMusic = AudioPlayer.player;
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            if(e.getSource()==btnStart){
                playMusic();
            }else if(e.getSource()==btnChange){
                changeMusic();
            }else{
                stopMusic();
            }
            
        }
        //음악 실행
        public void playMusic(){
            try {
                asMusic = new AudioStream(music);
                apMusic.start(asMusic);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //음악 변경
        public void changeMusic(){
            //파일 열기 다이얼로그
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio(wav,au,mid,rmf)""wav","au","mid","rmf");
            
            //만들어둔 JFileChooser에 파일 필터를 부착
            chooser.setFileFilter(filter);
            
            //파일 열기 다이얼로그 출력
            int ret = chooser.showOpenDialog(null);
            
            String filePath = chooser.getSelectedFile().getPath();
            String fileName = chooser.getSelectedFile().getName();
            
            //선택된 파일을 AudioStream 에 담기
            musicFile = new File(filePath);
            try {
                isMusic = new FileInputStream(musicFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        //음악 정지
        public void stopMusic(){
            apMusic.stop(asMusic);
        }
        //앨범 이미지 패널
        class ImgPanel2 extends JPanel{
            BufferedImage is;
            public ImgPanel2(BufferedImage is) {
                this.is = is;
                
            }
            
            public void imgChange(BufferedImage cImg){
                is = cImg;
            }
            
            @Override
            public void paint(Graphics g) {
                g.drawImage(is, 00300300null);
            }
            
            @Override
            public Dimension getPreferredSize() {
                
                return new Dimension(120120);
            }
        }
    }
    
}
 
cs

 

3.12 DeleteConfirmDialog

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
package Dialog;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
import Center.ShowPanel;
import DB.DBConnector;
 
public class DeleteConfirmDialog extends JFrame {
    
    private ShowPanel sp;
    private LinkedList<Integer> chkIDs;
    private DBConnector dbc;
    private JPanel btnPanel;
    
    public DeleteConfirmDialog() {
        setSize(500300);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        sp = new ShowPanel();
        chkIDs = sp.getChkIDs();
        dbc = new DBConnector();
        
        JLabel lbl = new JLabel("선택한 음악을 삭제하시겠습니까?");
        Font font = new Font("D2Coding", Font.BOLD, 20);
        lbl.setHorizontalAlignment((int)CENTER_ALIGNMENT);
        lbl.setFont(font);
        getContentPane().add(lbl, BorderLayout.CENTER);
        
        btnPanel = new JPanel();
        
        JButton btnOK = new JButton("확인");
        btnOK.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < chkIDs.size(); i++) {
                    dbc.deleteDB(chkIDs.get(i));
                }
                new SuccessDialog2();
                dispose();
            }
        });
        btnPanel.add(btnOK);
        
        JButton btnNO = new JButton("취소");
        btnNO.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                
            }
        });
        btnPanel.add(btnNO);
        
        getContentPane().add(btnPanel, BorderLayout.SOUTH);
        setVisible(true);
    }
}
cs

 

3.13 ListPlzDialog

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
package Dialog;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class ListPlzDialog extends JFrame implements ActionListener {
 
    public ListPlzDialog() {
        setSize(500300);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        JLabel lbl = new JLabel("음악 목록 보기에서 수정할 음악을 선택해 주세요.");
        Font font = new Font("D2Coding", Font.BOLD, 20);
        lbl.setHorizontalAlignment((int)CENTER_ALIGNMENT);
        lbl.setFont(font);
        getContentPane().add(lbl, BorderLayout.CENTER);
        
        JButton btn = new JButton("확인");
        btn.addActionListener(this);
        getContentPane().add(btn, BorderLayout.SOUTH);
        
        setVisible(true);
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        dispose();
        
    }
}
 
cs

 

3.14 ListPlzDialog2

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
package Dialog;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class ListPlzDialog2 extends JFrame implements ActionListener {
 
    public ListPlzDialog2() {
        setSize(500300);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        JLabel lbl = new JLabel("음악 목록 보기에서 재생할 음악을 선택해 주세요.");
        Font font = new Font("D2Coding", Font.BOLD, 20);
        lbl.setHorizontalAlignment((int)CENTER_ALIGNMENT);
        lbl.setFont(font);
        getContentPane().add(lbl, BorderLayout.CENTER);
        
        JButton btn = new JButton("확인");
        btn.addActionListener(this);
        getContentPane().add(btn, BorderLayout.SOUTH);
        
        setVisible(true);
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        dispose();
        
    }
}
 
cs

 

3.15 OneChkPlzDialog

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
package Dialog;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class OneChkPlzDialog extends JFrame implements ActionListener {
 
    public OneChkPlzDialog() {
        setSize(500300);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        JLabel lbl = new JLabel("수정할 음악을 하나만 선택해 주세요.");
        Font font = new Font("D2Coding", Font.BOLD, 20);
        lbl.setHorizontalAlignment((int)CENTER_ALIGNMENT);
        lbl.setFont(font);
        getContentPane().add(lbl, BorderLayout.CENTER);
        
        JButton btn = new JButton("확인");
        btn.addActionListener(this);
        getContentPane().add(btn, BorderLayout.SOUTH);
        
        setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        dispose();
        
    }
 
}
 
cs

 

3.16 OneChkPlzDialog2

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
package Dialog;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class OneChkPlzDialog2 extends JFrame implements ActionListener {
 
    public OneChkPlzDialog2() {
        setSize(500300);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        JLabel lbl = new JLabel("삭제할 음악을 선택해 주세요.");
        Font font = new Font("D2Coding", Font.BOLD, 20);
        lbl.setHorizontalAlignment((int)CENTER_ALIGNMENT);
        lbl.setFont(font);
        getContentPane().add(lbl, BorderLayout.CENTER);
        
        JButton btn = new JButton("확인");
        btn.addActionListener(this);
        getContentPane().add(btn, BorderLayout.SOUTH);
        
        setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        dispose();
        
    }
 
}
 
cs

 

3.17 SuccessDialog

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
package Dialog;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
 
public class SuccessDialog extends JFrame implements ActionListener {
 
    public SuccessDialog() {
        setSize(500300);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        JLabel lbl = new JLabel("데이터베이스에 저장되었습니다.");
        lbl.setHorizontalAlignment((int)CENTER_ALIGNMENT);
        getContentPane().add(lbl, BorderLayout.CENTER);
        
        JButton btn = new JButton("확인");
        btn.addActionListener(this);
        getContentPane().add(btn, BorderLayout.SOUTH);
        
        setVisible(true);
        
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        dispose();
    }
}
 
cs

 

3.18 SuccessDialog2

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
package Dialog;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
 
public class SuccessDialog2 extends JFrame implements ActionListener {
 
    public SuccessDialog2() {
        setSize(500300);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize(); 
        setLocation(screenSize.width /- 250 ,screenSize.height/- 150);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        JLabel lbl = new JLabel("성공적으로 삭제되었습니다.");
        lbl.setHorizontalAlignment((int)CENTER_ALIGNMENT);
        getContentPane().add(lbl, BorderLayout.CENTER);
        
        JButton btn = new JButton("확인");
        btn.addActionListener(this);
        getContentPane().add(btn, BorderLayout.SOUTH);
        
        setVisible(true);
        
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        dispose();
    }
}
 
cs

 

'Java > Java 프로젝트' 카테고리의 다른 글

Server and PieChart  (0) 2016.08.25
Java 임금 계산기  (0) 2016.08.11
COMMENT
━━━━ ◇ ━━━━
Java/Java 공부

DB에서 파일 가져오기

앞서 DB에 파일을 넣었다면, 이번에는 DB에서 파일을 가져오는것을 할 차례입니다.


FileOutputStream 을 사용하면 되겠죠?


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
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
public class BLOBOutputTest {
    private Connection con;
    private String driverName = "com.mysql.jdbc.Driver";
    private String dbURL = "jdbc:mysql://localhost:포트번호/DB이름";
    
    public BLOBOutputTest() {
        try {
            Class.forName(driverName);
            Connection con = DriverManager.getConnection(dbURL, "계정""비밀번호"); //JDBC연결
        
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM PDS");
 
            if(rs.next()){
                InputStream is = rs.getBinaryStream("FILE");
                String sql ="C:\\Users\\aristata\\Pictures\\Saved Pictures\\blobTest.png";
                FileOutputStream fos = new FileOutputStream(sql);
                byte[] buff = new byte[8192];
                int len;
                while( (len = is.read(buff)) > 0){
                    fos.write(buff, 0, len);
                }
                fos.close();
                is.close();
                rs.close();
            }
            con.close();
 
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        
        new BLOBOutputTest();
    }
 
}
 
cs



DB에 icon_01.png 파일이 들어있는 상태에서 blobTest.png 파일로 가져왔습니다. 

지정된 경로에 들어가서 확인을 해보니 파일이 생성되어 있는것을 확인할 수 있었습니다.

'Java > Java 공부' 카테고리의 다른 글

Java 누적합계가 100을 넘지 않는 가장 큰 수 찾기  (0) 2016.09.01
Java 숫자를 입력하고 각 자리의 합을 구해보자  (0) 2016.09.01
DB에 파일 집어넣기  (0) 2016.07.25
String 클래스  (0) 2016.07.18
메소드  (0) 2016.07.18
COMMENT
━━━━ ◇ ━━━━
Java/Java 공부

DB에 파일 집어넣기

BLOB 파일을 DB에 집어 넣는 것은 사실 별로 권장하지 않는다고 합니다.

왜냐하면 DB의 용량이 커져서 select 등의 sql문을 실행할때 많은 리소스를 필요하기 때문입니다.

그렇다고 안배울수는 없죠?

 

일단 수업시간에 선생님께서 요구한 사항들은 다음과 같습니다.

1. MySQL 로 DB와 테이블을 생성할것.

2. Eclipse 로 DB와 연결하여 임의의 경로에 들어있는 파일을 DB에 넣을것.

 

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
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class BLOBInputTest {
 
    //전역변수선언
    private Connection con;
    private String driverName = "com.mysql.jdbc.Driver";
    private String dbURL = "jdbc:mysql://localhost:포트번호/DB이름";
    
    public BLOBInputTest(String fileName) {
        try {
            Class.forName(driverName);
            con = DriverManager.getConnection(dbURL, "계정""비밀번호");
            
            int maxID = getMaxID(con) +1;
            File file = new File(fileName);
            int fileLength = (int)file.length();
            System.out.println("fileLength : "+fileLength);
            InputStream is = new FileInputStream(file);
            
            String sql ="insert into pds (id, filename, file) values (?,?,?)";
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, maxID);
            pstmt.setString(2, fileName);
            pstmt.setBinaryStream(3, is, fileLength);
            pstmt.executeUpdate();
            pstmt.close();
            con.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    protected int getMaxID(Connection con) throws SQLException{
        
        int maxID = 0;
        Statement stmt = con.createStatement();
        ResultSet result = stmt.executeQuery("select max(id) from pds");
        while(result.next()){
            maxID = result.getInt(1);
        }
        result.close();
        stmt.close();
        return maxID;
    }
    public static void main(String[] args) {
        String fileName = "C:\\Users\\aristata\\Pictures\\Saved Pictures\\icon_01.png";
        BLOBInputTest fileup = new BLOBInputTest(fileName);
        System.out.println("성공");
 
    }
 
}
 
cs

 

 

'Java > Java 공부' 카테고리의 다른 글

Java 숫자를 입력하고 각 자리의 합을 구해보자  (0) 2016.09.01
DB에서 파일 가져오기  (1) 2016.07.25
String 클래스  (0) 2016.07.18
메소드  (0) 2016.07.18
클래스  (0) 2016.07.18
COMMENT
━━━━ ◇ ━━━━
Android/Android 프로젝트

Android 일기장 만들기

주제 : 일기장 만들기


요구사항 : 

1. TabLayout, PagerAdapter 기능을 사용할 것.

2. ListView, ListAdapter 기능을 사용할 것.

3. Intent 기능을 사용할 것.

4. Dialog 기능을 사용할 것.

5. SQLite 기능을 사용할 것.


계획 :

1. 일기를 쓴다 -> DB에 저장한다. 

2. 일기를 본다 -> DB에서 불러온다.

3. 비밀번호를 설정한다 -> 일기를 볼때 비밀번호가 일치해야 볼수 있다.

4. 리스트뷰에서 클릭하여 수정, 롱클릭하여 삭제

5. 알림창은 다이얼로그와 새로운 액티비티를 만들어서 intent를 사용한다.

6. 각각의 카테고리는 탭레이아웃과 페이저어댑터를 이용하여 만든다.




실행 사진들








새 프로젝트를 생성하고 가장 먼저 할일은 Dependency 에 사용할 라이브러리 들을 추가하는 것이다.




▲ File -> Project Structure 




▲ app -> Dependency -> 더하기 단추 -> Library dependency




▲ design 추가




두번째로 할 일은 기본으로 설정되어 있는 액션바를 없애주는 것이다.




▲ res -> values -> styles.xml -> NoActionBar 로 바꿔준다.




▲ 메인 레이아웃에 툴바와 탭레이아웃, 뷰어페이저 등을 등록한다.




▼ 일기장 DB에서 사용할 Diary 클래스를 생성하고, 적당한 필드값들을 만든 후 getter, setter 를 생성한다.






▼ SQLiteOpenHelper 를 상속받는 클래스를 생성하고, 메소드를 오버라이드 한다.



▼ 생성자도 만들어 준다.





▼ FragmentStatePagerAdater 를 상속받는 클래스를 생성하고 필요한 메소드 들을 오버라이드 해준다.





이하는 코드 소스들


1. activity_main.xml


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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.aristata.a0720_01_diary_ver2.MainActivity">
 
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
 
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
 
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</LinearLayout>
 
cs



2. tab_setting.xml


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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="5dp">
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="비밀번호 사용"
            android:id="@+id/text_secret"
            android:textSize="20dp"
            android:layout_weight="1"
            android:gravity="center" />
 
        <Switch
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:id="@+id/switch1"
            android:layout_gravity="right"
            android:layout_weight="1"
            android:gravity="center" />
    </LinearLayout>
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp">
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="비밀번호 설정"
            android:id="@+id/textView"
            android:textSize="20dp"
            android:gravity="center"
            android:layout_weight="1" />
 
        <EditText
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:ems="10"
            android:id="@+id/secret_editText"
            android:gravity="center"
            android:layout_weight="1"
            android:visibility="invisible" />
    </LinearLayout>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="저장"
        android:id="@+id/secret_save_btn" />
 
</LinearLayout>
cs



3. tab_write.xml


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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <EditText
        android:id="@+id/edit_title_write"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="제목을 입력하세요."
        android:background="#e1f1cb"
        android:layout_weight="5" />
    <EditText
        android:id="@+id/edit_contents_write"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#efedbf"
        android:lines="15"
        android:hint="내용을 입력하세요."
        android:gravity="top|left"
        android:layout_weight="1" />
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="#e1f1cb">
 
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="저장"
            android:id="@+id/save_btn_write"
            android:layout_weight="1" />
 
    </LinearLayout>
 
</LinearLayout>
cs


4. tab_list.xml


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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="목록 보기"
        android:id="@+id/refresh_btn_list" />
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="7"
        android:gravity="center">
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="코드"
            android:id="@+id/textCode"
            android:gravity="center" />
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="제목"
            android:id="@+id/textTitle"
            android:gravity="center" />
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="날짜"
            android:id="@+id/textDate"
            android:layout_weight="1"
            android:gravity="center" />
    </LinearLayout>
 
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_diary"
        android:layout_weight="1" />
 
</LinearLayout>
cs


5. list_layout.xml


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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView_code"
        android:gravity="center" />
 
    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView_title"
        android:gravity="center" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView_date"
        android:layout_weight="1"
        android:gravity="center" />
</LinearLayout>
cs


6. passwd.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/key" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/check_pass"
        android:layout_gravity="center_horizontal"
        android:hint="비밀번호를 입력하세요" />
 
</LinearLayout>
cs


7. activity_diary_update.xml


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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.aristata.a0720_01_diary_ver2.Diary_Update">
 
    <EditText
        android:id="@+id/edit_title_update"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="제목을 입력하세요."
        android:background="#e1f1cb"
        android:layout_weight="5" />
    <EditText
        android:id="@+id/edit_contents_update"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#efedbf"
        android:lines="15"
        android:hint="내용을 입력하세요."
        android:gravity="top|left"
        android:layout_weight="1" />
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="#e1f1cb">
 
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="저장"
            android:id="@+id/save_btn_update"
            android:layout_weight="1" />
 
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="돌아가기"
            android:id="@+id/return_btn_update"
            android:layout_weight="1" />
 
    </LinearLayout>
</LinearLayout>
 
cs


8. Diary.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
package com.aristata.a0720_01_diary_ver2;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class Diary {
 
    private int code;
    private String title;
    private String date;
    private String contents;
 
    public int getCode() {
        return code;
    }
 
    public void setCode(int code) {
        this.code = code;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getDate() {
        return date;
    }
 
    public void setDate(String date) {
        this.date = date;
    }
 
    public String getContents() {
        return contents;
    }
 
    public void setContents(String contents) {
        this.contents = contents;
    }
}
 
cs


9. DiaryDBHelper.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
package com.aristata.a0720_01_diary_ver2;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class DiaryDBHelper extends SQLiteOpenHelper {
 
 
    public DiaryDBHelper(Context context) {
        super(context, "Diary"null1);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE diary (" +
                "'code' INTEGER PRIMARY KEY AUTOINCREMENT," +
                "`title` TEXT," +
                "`date` TEXT," +
                "`contents` TEXT);";
        db.execSQL(sql);
 
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "drop table if exists diary";
        db.execSQL(sql);
 
        onCreate(db);
    }
}
 
cs


10. DiaryPassDBHelper.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
package com.aristata.a0720_01_diary_ver2;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class DiaryPassDBHelper extends SQLiteOpenHelper {
    public DiaryPassDBHelper(Context context) {
        super(context, "Password"null1);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE passwd (" +
                "'pass' TEXT);";
        db.execSQL(sql);
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "drop table if exists passwd";
        db.execSQL(sql);
 
        onCreate(db);
    }
}
 
cs


11. DiaryListAdapter.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
package com.aristata.a0720_01_diary_ver2;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
 
import java.util.ArrayList;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class DiaryListAdapter extends BaseAdapter {
    private Context ctx;
    private int layout;
    private ArrayList<Diary> data;
    private LayoutInflater inflater;
 
    public DiaryListAdapter(Context ctx, int layout, ArrayList<Diary> data) {
        this.ctx = ctx;
        this.layout = layout;
        this.data = data;
        inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return data.size();
    }
 
    @Override
    public Object getItem(int position) {
        return data.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null){
            convertView = inflater.inflate(layout,parent,false);
        }
        TextView textView_code_list = (TextView)convertView.findViewById(R.id.textView_code);
        TextView textView_title_list = (TextView)convertView.findViewById(R.id.textView_title);
        TextView textView_date_list = (TextView)convertView.findViewById(R.id.textView_date);
        textView_code_list.setText(data.get(position).getCode()+"");
        textView_title_list.setText(data.get(position).getTitle()+"");
        textView_date_list.setText(data.get(position).getDate()+"");
        return convertView;
    }
}
 
cs


12. Tab_Pager_Adapter.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
package com.aristata.a0720_01_diary_ver2;
 
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class Tab_Pager_Adapter extends FragmentStatePagerAdapter {
    private int tabCount;
 
    public Tab_Pager_Adapter(FragmentManager fm, int tabCount) {
        super(fm);
        this.tabCount = tabCount;
    }
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 1:
                MainActivity.Diary_Write diaryWrite = new MainActivity.Diary_Write();
                return diaryWrite;
            case 2:
 
                MainActivity.Diary_List diaryList = new MainActivity.Diary_List();
                return diaryList;
            case 0:
                MainActivity.Diary_Setting diarySetting = new MainActivity.Diary_Setting();
                return diarySetting;
            default:
                return null;
        }
    }
 
    @Override
    public int getCount() {
        return tabCount;
    }
}
 
cs


13. MainActivity.java


package com.aristata.a0720_01_diary_ver2;
 
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;
 
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
 
public class MainActivity extends AppCompatActivity {
 
    //메인 엑티비티 전역변수
    private static TabLayout tabLayout;
    private static ViewPager viewPager;
    private static ArrayList<Diary> data;
    public static DiaryDBHelper dbHelper;
    public static DiaryPassDBHelper pdbHelper;
    public static SQLiteDatabase db;
 
 
    //Tab_Write 전역변수
    public static EditText edit_title, edit_contents;
    public static Button save_btn;
 
    //Tab_List 전역변수
    public static Button refresh_btn;
    public static ListView list_diary;
    public static DiaryListAdapter listAdapter;
 
    //Tab_Setting 전역변수
    public static Switch secretSwitch;
    public static EditText secretEditText;
    public static Button secretSaveBtn;
 
    public static EditText checkPass;
    public static int flag = 0;
    public static int flag2 = 0;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //디비 핼퍼 객체 생성
        dbHelper = new DiaryDBHelper(this);
        pdbHelper = new DiaryPassDBHelper(this);
        data = new ArrayList<>();
 
        //커스텀 툴바의 리소스 연결
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
 
        //액션바를 커스텀 툴바로 설정
        setSupportActionBar(toolbar);
 
        //커스텀 탭 레이아웃 리소스 연결
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
 
        //탭 레이아웃에 탭 추가
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_settings_white_48dp));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_create_white_48dp));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_visibility_white_48dp));
 
 
        //탭 배치 설정
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
 
        //커스텀 뷰페이지 리소스 연결
        viewPager = (ViewPager) findViewById(R.id.pager);
 
        //페이지 어답터 객체 생성
        Tab_Pager_Adapter pagerAdapter = new Tab_Pager_Adapter(getSupportFragmentManager(), tabLayout.getTabCount());
 
        //뷰 페이지 어답터 설정
        viewPager.setAdapter(pagerAdapter);
 
        //페이지에 변화가 생기면 ?
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        //viewPager.addOnPageChangeListener();
 
        //탭 선택 이벤트
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
 
            }
 
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
 
            }
 
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
 
            }
        });
 
 
    }//end of onCreate -------------------------------------------------------
 
    //Diary_Write inner class
    public static class Diary_Write extends Fragment{
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.tab_write, container, false);
            edit_title = (EditText) view.findViewById(R.id.edit_title_write);
            edit_contents = (EditText) view.findViewById(R.id.edit_contents_write);
            save_btn = (Button) view.findViewById(R.id.save_btn_write);
            save_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    InsertDB();
                }
            });
            return view;
        }
    }
 
    //Diary_List inner class
    public static class Diary_List extends Fragment{
 
        @Nullable
        @Override
        public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
            final View view = inflater.inflate(R.layout.tab_list, container, false);
            flag = 1;
            refresh_btn = (Button) view.findViewById(R.id.refresh_btn_list);
            refresh_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(secretSwitch.isChecked()){
                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                        alertDialog.setMessage("비밀번호를 입력하세요");
                        View dialogview = inflater.inflate(R.layout.passwd, container, false);
                        alertDialog.setView(dialogview);
                        checkPass = (EditText)dialogview.findViewById(R.id.check_pass);
 
                        alertDialog.setPositiveButton("확인"new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String cp = checkPass();
                                if(checkPass.getText().toString().equals(cp)){
                                    list_diary = (ListView) view.findViewById(R.id.list_diary);
                                    data = showDB();
                                    listAdapter = new DiaryListAdapter(getContext(), R.layout.list_layout, data);
                                    list_diary.setAdapter(listAdapter);
                                    list_diary.setOnItemClickListener( new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            Intent intent = new Intent(getContext(), Diary_Update.class);
                                            int code = data.get(position).getCode();
                                            intent.putExtra("code", code);
                                            startActivity(intent);
                                        }
                                    });
                                    list_diary.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                                        @Override
                                        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                                            alertDialog.setMessage(data.get(position).getTitle()+"을(를) 삭제하시겠습니까?");
                                            alertDialog.setPositiveButton("삭제"new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    int code = data.get(position).getCode();
                                                    deleteDB(code);
                                                    showDB();
                                                    listAdapter.notifyDataSetChanged();
                                                }
                                            });
                                            alertDialog.setNegativeButton("취소"new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.cancel();
                                                }
                                            });
                                            alertDialog.show();
                                            return false;
                                        }
                                    });
                                }else{
                                    Toast.makeText(getContext(), "비밀번호가 틀렸습니다.", Toast.LENGTH_SHORT).show();
                                    list_diary = (ListView) view.findViewById(R.id.list_diary);
                                    data = showDB();
                                    listAdapter = null;
                                    list_diary.setAdapter(listAdapter);
                                }
                            }
                        });
                        alertDialog.show();
                    }else{
                        list_diary = (ListView) view.findViewById(R.id.list_diary);
                        data = showDB();
                        listAdapter = new DiaryListAdapter(getContext(), R.layout.list_layout, data);
                        list_diary.setAdapter(listAdapter);
                        list_diary.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(getContext(), Diary_Update.class);
                                int code = data.get(position).getCode();
                                intent.putExtra("code", code);
                                startActivity(intent);
                            }
                        });
                        list_diary.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                            @Override
                            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                                alertDialog.setMessage(data.get(position).getTitle()+"을(를) 삭제하시겠습니까?");
                                alertDialog.setPositiveButton("삭제"new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        int code = data.get(position).getCode();
                                        deleteDB(code);
                                        showDB();
                                        listAdapter.notifyDataSetChanged();
                                    }
                                });
                                alertDialog.setNegativeButton("취소"new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                });
                                alertDialog.show();
                                return false;
                            }
                        });
                    }
 
 
                }
            });
            if(flag == 1){
                return view;
            }else{
                return null;
            }
 
 
        }
    }
 
    //환경설정 inner class
    public static class Diary_Setting extends Fragment{
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.tab_setting, container, false);
            secretSwitch = (Switch)view.findViewById(R.id.switch1);
            secretEditText = (EditText)view.findViewById(R.id.secret_editText);
            secretSaveBtn = (Button)view.findViewById(R.id.secret_save_btn);
            secretSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        //On
                        secretEditText.setVisibility(View.VISIBLE);
 
                    }else{
                        //Off
                        secretEditText.setVisibility(View.INVISIBLE);
 
 
                    }
                }
            });
            secretSaveBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str = secretEditText.getText().toString();
                    passDB(str);
                }
            });
            return view;
        }
    }
 
 
    //일기 쓰기 메소드
    public static void InsertDB(){
        db = dbHelper.getWritableDatabase();
        String sql = "insert into diary ('title', 'date', 'contents') values(?,?,?)";
        SQLiteStatement st = db.compileStatement(sql);
        st.bindString(1,edit_title.getText().toString());
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yy년 MM월 dd일 HH시 mm분 ss초");
        String writeTime = sdf.format(date);
        st.bindString(2,writeTime);
        st.bindString(3,edit_contents.getText().toString());
        st.execute();
        db.close();
        edit_title.setText("");
        edit_contents.setText("");
    }
 
    //일기 목록 보기 메소드
    public static ArrayList<Diary> showDB(){
        data.clear();
        db = dbHelper.getReadableDatabase();
        String sql = "select * from diary";
        Cursor cursor = db.rawQuery(sql, null);
        while(cursor.moveToNext()){
            Diary diary = new Diary();
            diary.setCode(cursor.getInt(0));
            diary.setTitle(cursor.getString(1));
            diary.setDate(cursor.getString(2));
            diary.setContents(cursor.getString(3));
            data.add(diary);
        }
        cursor.close();
        db.close();
        return data;
    }
 
    //일기 삭제 메소드
    public static void deleteDB(int code){
        db = dbHelper.getReadableDatabase();
        String sql = "delete from diary where code="+code;
        db.execSQL(sql);
        db.close();
    }
 
    //비밀번호 입력 메소드
    public static void passDB(String str){
        db = pdbHelper.getWritableDatabase();
        String sql = "insert into passwd values('"+str+"')";
        db.execSQL(sql);
        db.close();
        secretEditText.setText("");
    }
    //비밀번호 확인 메소드
    public static String checkPass(){
        db = pdbHelper.getReadableDatabase();
        String sql = "select * from passwd";
        Cursor cursor = db.rawQuery(sql, null);
        String pass="";
        while(cursor.moveToNext()){
            pass = cursor.getString(0);
        }
        cursor.close();
        db.close();
        return pass;
    }
 
}
 
cs


14. Diary_Update.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
package com.aristata.a0720_01_diary_ver2;
 
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class Diary_Update extends AppCompatActivity {
    private Intent intent;
    private EditText editText1, editText2;
    private int code;
    private Button btn1, btn2;
    private DiaryDBHelper dbHelper;
    private SQLiteDatabase db;
    private Diary diary = new Diary();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary__update);
        intent = getIntent();
 
        dbHelper = new DiaryDBHelper(getApplicationContext());
 
        editText1 = (EditText)findViewById(R.id.edit_title_update);
        editText2 = (EditText)findViewById(R.id.edit_contents_update);
 
        code = intent.getExtras().getInt("code");
 
        btn1 = (Button)findViewById(R.id.save_btn_update);
        btn2 = (Button)findViewById(R.id.return_btn_update);
 
        searchDiary(code);
        editText1.setText(diary.getTitle().toString());
        editText2.setText(diary.getContents().toString());
 
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDB(code);
                finish();
            }
        });
 
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    public Diary searchDiary(int code){
        db = dbHelper.getReadableDatabase();
        String sql = "select * from diary where code="+code;
        Cursor cursor = db.rawQuery(sql, null);
        while(cursor.moveToNext()){
            diary.setTitle(cursor.getString(1));
            diary.setContents(cursor.getString(3));
        }
        cursor.close();
        db.close();
        return diary;
    }
    public void updateDB(int code){
        db = dbHelper.getWritableDatabase();
        String sql = "update diary set title=?, contents=? where code="+code;
        SQLiteStatement st = db.compileStatement(sql);
        st.bindString(1,editText1.getText().toString());
        st.bindString(2,editText2.getText().toString());
        st.execute();
        db.close();
    }
}
 
cs


COMMENT
━━━━ ◇ ━━━━
Java/Java 공부

String 클래스

자바에서는 문자열을 객체로 취급한다. 

자바에서 우리에게 제공하는 String 클래스가 그것이다. 

클래스가 누군가에 의해 이미 작성되어 있다면, 우리는 객체를 생성하여 사용할 수 있다.




3번 라인의 코드를 실행시키면 String 클래스의 객체가 하나 생성된다. 

여기서 s 는 참조 변수로서 생성된 객체를 가리키는 변수이다. 

기초 변수는 값을 변수 안에 저장하지만 참조 변수는 객체의 주소가 저장된다. 
5번 라인을 보면 문자열을 그냥 쌍따옴표("") 안에 입력한 다음 참조 변수에 저장하고 있다. 

문자열은 자주 사용되므로 new 연산자를 사용하지 않고 문자열 상수로 표기해도 자동적으로 객체가 생성된다. 

객체가 생성된 후에 객체의 메소드를 이용하려면 도트 연산자(dot operator)를 사용한다. 

도트 연산자는 점(.)을 말한다. 

예를 들어서 String 클래스는 length() 라는 이름의 메소드를 가지고 있다. 

length() 메소드는 문자열의 길이를 반환하는 메소드 이다.



7번 라인을 보면 a.length()를 사용하여 문자열 a 의 개수가 17글자 임을 알수 있다.




위 사진은 String 클래스에서 제공하는 메소드 들이다. 

APIs 를 참고하면 더욱 자세하게 알 수 있다.
http://docs.oracle.com/javase/8/docs/api/



위와 같이 String 클래스의 메소드를 호출하여서 문자열을 결합하거나 문자열에 대한 연산을 실행 할 수 있다.

여기서 한가지 더 추가로 알고 있으면 좋은것은, 

문자열과 기초 자료형 변수를 결합하게 되면 자동적으로 기초 자료형을 문자열로 변환한다는 것이다. 




라인6을 보면 int type x 와 String 상수 "결과값은 "이 더해져 "결과값은 20" 이라는 문자열에 출력되었다. 

int 형 이 문자열로 자동 형변환 되었기 때문이다.


11번 라인과 12번 라인을 보면 문자열과 수치값이 합쳐지면, 

연산의 결과가 나오는것이 아니라 문자열의 결합으로 간주한다는것을 알 수 있다.

반대의 경우에는 어떻게 해야 할까? 

자바에서는 정수나 실수와 같은 기초 자료형을 제외하고는 모든 것이 객체로 되어 있다. 

하지만 어떤 경우에는 기초 자료형도 객체로 포장하고 싶은 경우가 있다. 

이때 사용되는 것이 랩퍼 클래스(wrapper class)이다.




랩퍼 클래스도 몇몇 메소드 들을 제공하고 있다. 
특히 저장된 값을 다른 자료형으로 변환하는 메소드를 자주 사용한다.



문자열과 수치형이 결합하면, 수치형이 자동으로 문자열로 형변환 된 다음 결합된다고 앞서 이야기 했다. 
랩퍼클래스의 메소드를 사용하여 정수형 x 를 문자열 xx로 변환한 다음 둘을 합한 결과를 출력하였더니 
"100100" 
이 출력되는 것을 확인 할 수 있다.



'Java > Java 공부' 카테고리의 다른 글

DB에서 파일 가져오기  (1) 2016.07.25
DB에 파일 집어넣기  (0) 2016.07.25
메소드  (0) 2016.07.18
클래스  (0) 2016.07.18
객체 지향 프로그래밍  (0) 2016.07.18
COMMENT
━━━━ ◇ ━━━━
Java/Java 공부

메소드

메소드는 붕어빵 굽는 기계와 유사하다. 붕어빵 기계에 밀가루 반죽과 팥을 넣으면 붕어빵이 나온다. 마찬가지로 메소드는 매개변수를 집어넣으면 정의된 반환형으로 결과물이 도출된다.

메소드는 다음과 같은 구조를 가진다.



위 코딩에서 메소드는 9번~11번 사이의 코드들 이다.
public : 접근 제어자 , public 은 아무나 가져다 쓸수 있다는 뜻이다.
static : 메모리에 항상 상주한다는 뜻이다. main 이 static 타입 이기 때문에 메인에서 직접 사용하는 메소드 들도 static 타입 이어야 사용가능하다.
int : 반환형, 메소드를 실행한 결과 반환되는 데이터의 타입을 뜻한다.
add : 메소드의 이름이다. 해당 메소드를 호출할때 이 이름으로 호출을 한다.
(int x, int y) : 인수, 매개변수, 해당 메소드에서 사용되는 재료와 같다. 위에서 언급했던 밀가루 반죽과 팥 등이 바로 이것이다.
return : 메소드의 결과물을 반환한다.

5번줄은 add 라는 메소드를 실행하는데, 인수들로 정수 3 과 5를 사용하고, 그 결과물을 int타입의 변수 result 에 저장한다.
add 라는 메소드는 내가 정의하기를 매개변수 x 와 y 를 넣어서 x+y를 반환하기 때문에 3 + 5 의 결과 8이 변수 result 에 저장된다.
6번줄에서 콘솔창에 변수 result를 출력하여 그 결과가 8임을 확인 할 수 있다.

위의 설명에서 인수(argument)와 매개변수(parameter) 라는 용어를 혼재하여 사용하였는데, 구체적인 의미는 메소드를 호출하는 곳에서 메소드 호출시 전달하는 값을 인수라고 하고, 메소드에서 값을 받을 때 사용하는 변수를 매개변수라고 부른다. 부르는 용어는 다르지만 보기에 따라 같은 의미이고, 결국 준것을 그대로 받아서 사용하는 개념이므로 매개변수와 인수의 타입이 서로 일치하여야 한다. 

반환하는 결과 값이 없는 경우에는 int 자리에 void를 사용한다.



코드 17~21을 보자.
Car 라는 클래스는 start라는 메소드를 가지고 있다. start 메소드는 int 타입의 매개변수 x 를 입력받아서 "x초 뒤에 차가 출발 합니다." 라는 문구를 콘솔에 출력하고 특별히 반환하는 값은 없다.
다시 코드 7~8을 보자.
start 메소드를 사용하기 위해서 start 메소드가 있는 Car 클래스의 객체를 우선 생성한다. 이때 Car 클래스를 가리키는 변수명은 car 이다. 변수명인 car 뒤 에 점(.)을 찍으면 Car 클래스 안에 들어있는 메소드들을 사용할 수 있다. 여기서 start 메소드를 사용하자. 인수는 10으로 주었다. 그 결과 Car 클래스의 start메소드가 실행되어 "10초 뒤에 차가 출발 합니다." 라는 문구가 콘솔창에 출력되었음을 확인 할 수 있다.

  

'Java > Java 공부' 카테고리의 다른 글

DB에 파일 집어넣기  (0) 2016.07.25
String 클래스  (0) 2016.07.18
클래스  (0) 2016.07.18
객체 지향 프로그래밍  (0) 2016.07.18
break 와 continue  (0) 2016.07.18
COMMENT
1 ··· 4 5 6 7 8 9