Java - GUI,login

2020. 7. 26. 20:51Java

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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
import java.awt.BorderLayout;
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
 
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Pattern;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import java.awt.Color;
import javax.swing.JScrollBar;
 
public class Ex extends JFrame {
    JTextField tfip,tfname;
    JPasswordField pfpass;
    private JTextField tfUserName;
    private JTextField tfNum;
    private JTextField tfName;
    private JTextField tfID;
    private JTextField tfpassword;
    private JTextField tfJumin;
    private JTable table;
    private JTable table_1;
    JButton btnLogin;
    JButton btnAdd;
    JButton btnList;
    JButton btnDelete;
    JButton btnUpdate;
    customerDAO dao=customerDAO.getInstance();
    private boolean isLogin=false;//로그인 여부 체크변수
    
    public Ex() {
        showFrame();
    }
 
    private void showFrame() {
        setTitle("고객관리 프로그램");
        setBounds(600400700380);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);
        
        JLabel lbIp = new JLabel("IP");
        lbIp.setHorizontalAlignment(SwingConstants.RIGHT);
        lbIp.setBounds(44172015);
        getContentPane().add(lbIp);
        
        tfip = new JTextField("localhost");
        tfip.setEditable(false);
        tfip.setBounds(681410421);
        getContentPane().add(tfip);
        tfip.setColumns(10);
        
        JLabel lblName = new JLabel("Username");
        lblName.setHorizontalAlignment(SwingConstants.RIGHT);
        lblName.setBounds(190176315);
        getContentPane().add(lblName);
        
        tfUserName = new JTextField("admin");
        tfUserName.setEditable(false);
        tfUserName.setBounds(260148221);
        getContentPane().add(tfUserName);
        tfUserName.setColumns(10);
        
        JLabel lblPass = new JLabel("Password");
        lblPass.setHorizontalAlignment(SwingConstants.RIGHT);
        lblPass.setBounds(344176915);
        getContentPane().add(lblPass);
        
        pfpass = new JPasswordField();
        pfpass.setBounds(426148221);
        getContentPane().add(pfpass);
        
         btnLogin = new JButton("Login");
        btnLogin.setBounds(536139723);
        getContentPane().add(btnLogin);
        
        JLabel lblNum = new JLabel("번 호");
        lblNum.setHorizontalAlignment(SwingConstants.RIGHT);
        lblNum.setBounds(12735015);
        getContentPane().add(lblNum);
        
        JLabel lblName2 = new JLabel("이 름");
        lblName2.setHorizontalAlignment(SwingConstants.RIGHT);
        lblName2.setBounds(121105015);
        getContentPane().add(lblName2);
        
        JLabel lblAge = new JLabel("ID");
        lblAge.setHorizontalAlignment(SwingConstants.RIGHT);
        lblAge.setBounds(121465015);
        getContentPane().add(lblAge);
        
        JLabel lblMail = new JLabel("Password");
        lblMail.setHorizontalAlignment(SwingConstants.RIGHT);
        lblMail.setBounds(01826215);
        getContentPane().add(lblMail);
        
        JLabel lblJumin = new JLabel("주민번호");
        lblJumin.setHorizontalAlignment(SwingConstants.RIGHT);
        lblJumin.setBounds(122195215);
        getContentPane().add(lblJumin);
        
        tfNum = new JTextField();
        tfNum.setEditable(false);
        tfNum.setBounds(75709721);
        getContentPane().add(tfNum);
        tfNum.setColumns(10);
        
        tfName = new JTextField();
        tfName.setBounds(751109721);
        getContentPane().add(tfName);
        tfName.setColumns(10);
        
        tfID = new JTextField();
        tfID.setBounds(751439721);
        getContentPane().add(tfID);
        tfID.setColumns(10);
        
        tfpassword = new JTextField();
        tfpassword.setBounds(751799721);
        getContentPane().add(tfpassword);
        tfpassword.setColumns(10);
        
        tfJumin = new JTextField();
        tfJumin.setBounds(752169721);
        getContentPane().add(tfJumin);
        tfJumin.setColumns(10);
        
         btnAdd = new JButton("회원추가");
        btnAdd.setBounds(1382949723);
        getContentPane().add(btnAdd);
        
         btnList = new JButton("회원목록");
        btnList.setBounds(2472949723);
        getContentPane().add(btnList);
        
        btnDelete = new JButton("회원삭제");
        btnDelete.setBounds(3562949723);
        getContentPane().add(btnDelete);
        
 
        btnUpdate = new JButton("회원정보수정");
        btnUpdate.setBounds(46329411423);
        getContentPane().add(btnUpdate);
        
//        JPanel panel = new JPanel();
//        panel.setBounds(190, 57, 474, 227);
//        getContentPane().add(panel);
        
        JScrollPane scrollPane = new JScrollPane();//패널의 역할도 하기 때문에 패널에 add하지 않아도 된다!!
        scrollPane.setBounds(19057474227);
        getContentPane().add(scrollPane);
        
        table = new JTable();
        scrollPane.setViewportView(table);
        
        
        Vector<String> columnNames=new Vector<String>(
                Arrays.asList("번호","이름","ID","패스워드","주민번호")
                );
        
//        DefaultTableModel model=new DefaultTableModel(columnNames, 0);
        
        //테이블 셀 편집이 불가능하도록 설정할 경우
        DefaultTableModel model=new DefaultTableModel(columnNames, 0) {
            
            //isCellEditable() 메서드 오버라이딩하여 false 리턴
            @Override
            public boolean isCellEditable(int row, int column) {
                
                return false;
            }
        };
        
        table.setModel(model);
        
        
        btnLogin.addActionListener(listener);
        btnAdd.addActionListener(listener);
        btnList.addActionListener(listener);
        btnDelete.addActionListener(listener);
        btnUpdate.addActionListener(listener);
        
        table.addMouseListener(new MouseAdapter() {
 
            @Override
            public void mouseClicked(MouseEvent arg0) {
                showCustomerInfo();
            }
            
            
        });
        
        
        
        setVisible(true);
    }
    ActionListener listener=new ActionListener() {
        
        @Override
        public void actionPerformed(ActionEvent e) {
            if(e.getSource()==btnLogin) {
                login();
            }else if(e.getSource()==btnAdd) {
                insert();
            }else if(e.getSource()==btnList) {
                select();
            }else if(e.getSource()==btnDelete) {
                delete();
            }else if(e.getSource()==btnUpdate) {
                update();
            }
        }
    };
    
    public void login() {
        //현재 로그인 여부를 판별하여 로그인 상태가 아닐 때 로그인 작업 수행하고,
        //로그인 상태일때 로그아웃 작업 수행
        if(!isLogin) {//로그인 상태가 아닐 경우 로그인 작업 수행
            
            String dbip=tfip.getText();
            String user=tfUserName.getText();
            String pass=new String(pfpass.getPassword());
            if(user.length()==0) {
                JOptionPane.showMessageDialog(null"ID을 입력하세요","실패",JOptionPane.ERROR_MESSAGE);
                tfUserName.requestFocus();
                return;
            }else if(pass.length()==0) {
                JOptionPane.showMessageDialog(null"비밀번호를 입력하세요","실패",JOptionPane.ERROR_MESSAGE);
                pfpass.requestFocus();
                return;
            }
            
            boolean result;
            try {
                result = dao.login(dbip,user,pass);
                if(result) {
                    JOptionPane.showMessageDialog(null"로그인 성공");
                    tfUserName.setEditable(false);
                    pfpass.setEditable(false);
                    btnLogin.setText("Logout");
                    isLogin=true;
                    return;
                }
            }
            catch (LoginFailException e1) {
                JOptionPane.showMessageDialog(null"로그인 실패","오류",JOptionPane.ERROR_MESSAGE);
                e1.printStackTrace();
            }
        }else {//로그인 상태일 경우 로그아웃 작업 수행
            //Logout 버튼 텍스스트를 Login 으로 변경
            btnLogin.setText("Login");
            //DB접속을 위한 id와 password 입력창을 편집 가능하도록 변경및 패스워드 제거
            tfUserName.setEditable(true);
            pfpass.setText("");
            pfpass.setEditable(true);
            isLogin=false;
        }
        
    }
        
    
    
    public void insert() {
        if(!isLogin) {
            JOptionPane.showMessageDialog(null"로그인 필수","경고",JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 입력받은 데이터 가져오기
        String name=tfName.getText();
        String id= tfID.getText();
        String password=tfpassword.getText();
        String jumin=tfJumin.getText();
        
        if(name.length()==0) {
            JOptionPane.showMessageDialog(null"이름을 입력하세요.","경고",JOptionPane.ERROR_MESSAGE);
            tfName.requestFocus();
            return;
        }else if(id.length()==0) {
            JOptionPane.showMessageDialog(null"ID를 입력하세요.","경고",JOptionPane.ERROR_MESSAGE);
            tfID.requestFocus();
            return;
        }else if(password.length()==0) {
            JOptionPane.showMessageDialog(null"Password를 입력하세요","경고",JOptionPane.ERROR_MESSAGE);
             tfpassword.requestFocus();
             return;
        }else if(jumin.length()==0) {
            JOptionPane.showMessageDialog(null"주민번호를 입력하세요","경고",JOptionPane.ERROR_MESSAGE);
            tfJumin.requestFocus();
            return;
        }
         
         boolean result=dao.Insert(name,id,password,jumin);
         if(result) {
             JOptionPane.showMessageDialog(null"회원추가 성공");
             tfName.setText("");
             tfID.setText("");
             tfpassword.setText("");
             tfJumin.setText("");
             
         }else {
             JOptionPane.showMessageDialog(null"회원추가 실패","경고",JOptionPane.ERROR_MESSAGE);
         }
         
         //새로운 테이블 정보 갱신
         select();
    }
    
    public void delete() {
        if(!isLogin) {
            JOptionPane.showMessageDialog(null"로그인 필수","경고",JOptionPane.ERROR_MESSAGE);
            return;
        }
        //삭제할 회원번호를 입력받는 다이얼로그 표시를 위해
        //JOptionPane 객체의 showInputDialog()메서드 호출
        //입력받은 데이터는 String 타입으로 리턴됨
        //데이터 입력없이 확인 버튼 누르면 널스트링("")리턴됨
        //취소 버튼 클릭시 null 리턴됨
        String inputData= JOptionPane.showInputDialog(this," 삭제할 회원번호를 입력하세요.");
        
        //리턴값이 null 일 경우 현재 메서드 그냥 종료(return)
        //널스트링("")일 경우 "삭제할 번호를 입력하세요" 메세지 출력 후 return
        while(inputData==null || inputData.length()==0) {
            if(inputData==null) {
                return;
            }else if(inputData.length()==0) {
                JOptionPane.showMessageDialog(this"삭제할 번호를 입력하세요","입력 오류",JOptionPane.ERROR_MESSAGE);
                inputData=JOptionPane.showInputDialog(this,"삭제할 회원번호를 입력하세요");
            }
        }
        
        String regex="^[0-9]{1,}$";
        if(!Pattern.matches(regex, inputData)) {
            JOptionPane.showMessageDialog(this"번호만 입력가능","입력오류",JOptionPane.ERROR_MESSAGE);
            return;
        }
        //입력된 데이터가 있을 경우
        //DAO 객체의 delete()메서드를 호출하여 삭제할 번호 전달 후 결과 리턴
                
        int idx=Integer.parseInt(inputData);
        boolean result=dao.Delete(idx);
        if(result) {
            JOptionPane.showMessageDialog(this"삭제 성공");
        }else {
            JOptionPane.showMessageDialog(this,"삭제 실패","입력오류",JOptionPane.ERROR_MESSAGE);
        }
        //새로운 테이블 정보 갱신
        select();
        
    }
    
    public void select() {
        if(!isLogin) {
            JOptionPane.showMessageDialog(null"로그인 필수","경고",JOptionPane.ERROR_MESSAGE);
            return;
        }
        //DAO 객체의 select()메서드를 호출하여 전체 회원 정보를 Vector 객체로 리턴받기
        //리턴받은 Vector 객체 내의 모든 정보출력
        Vector<Vector> item=dao.select();
        DefaultTableModel model=(DefaultTableModel)table.getModel();
        model.setRowCount(0);//데이터를 추가하기전에 rowCount 를 0으로 초기화 필수!!
        for(Vector<Vector> data:item) {
            
            model.addRow(data);
        }
    }
    
    public void update() {
        if(!isLogin) {
            JOptionPane.showMessageDialog(null"로그인 필수","경고",JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        String name=tfName.getText();
        String id= tfID.getText();
        String password=tfpassword.getText();
        String jumin=tfJumin.getText();
        int idx=Integer.parseInt(tfNum.getText());
        boolean result=dao.update(name, id, password, jumin,idx);
        if(result) {
            JOptionPane.showMessageDialog(this"정보수정완료");
            select();
        }else {
            JOptionPane.showMessageDialog(this"입력창을 확인하세요.","수정실패",JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public void showCustomerInfo() {
//        System.out.println(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
        
        //클릭된 셀의 행번호를 고정하여 0~4번열 까지 데이터를
        //좌측 회원정보 입력 텍스트 필드에 차례대로 표시
        //단, getValueAt() 메서드 리턴타입이 Object 이므로 String 타입으로 변환 필요
        tfNum.setText(table.getValueAt(table.getSelectedRow(),0).toString());
        tfName.setText(table.getValueAt(table.getSelectedRow(),1).toString());
        tfID.setText(table.getValueAt(table.getSelectedRow(),2).toString());
        tfpassword.setText(table.getValueAt(table.getSelectedRow(),3).toString());
        tfJumin.setText(table.getValueAt(table.getSelectedRow(),4).toString());
    }
    
    
    
    
    public static void main(String[] args) {
        new Ex();
    }
}
 
 
class LoginFailException extends Exception{
    public LoginFailException(String message) {
        super(message);
    }
}
 
 
 
//-------------DAO------------------
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
 
public class customerDAO {
    
    String ip;
    
    private customerDAO() {}
    private static customerDAO instance= new customerDAO();
    public static customerDAO getInstance() {
        return instance;
    }
    public static Connection con=null;
    public static ResultSet rs=null;
    public static PreparedStatement pstmt=null;
    
    public Connection getConnection(String ip)throws Exception {
        
        String driver="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://"+ip+":3306/java5";
        String user= "root";
        String password= "1234";
        
            Class.forName(driver);
            con=DriverManager.getConnection(url, user, password);
        
        return con;
    }
    //데이터베이스 자원 반환(close()) 메서드
    private void closeDb() {
        if(rs!=null)try {rs.close();}catch(Exception e){}
        if(pstmt!=null)try {pstmt.close();}catch(Exception e){}
        if(con!=null)try {con.close();}catch(Exception e){}
    }
    
    
    //IP주소, 계정명, 패스워드를 전달받아 로그인 기능을 수행하는 login() 메서드 정의
    public boolean login(String ip,String dbUsername,String dbPassword)throws LoginFailException {
        this.ip=ip;
        
        //getConnection()메서드를 호출하여 Connection객체 가져오기
        boolean result=false;
        try {
            con=getConnection(ip);
            String sql="select password from customer where id=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1, dbUsername);
            rs=pstmt.executeQuery();
            if(rs.next()) {
                if(dbPassword.equals(rs.getString(1))) {
                    result=true;
                }else {
                    throw new LoginFailException("비밀번호 틀립니다.");
                }
            }else {
                throw new LoginFailException("존재하지 않는 아이디");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (LoginFailException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            closeDb();
        }
        return result;
    }
    //이름, 아이디, 패스워드, 주민번호를 전달받아 customer 테이블에 추가후 성공여부 리턴
 
    public boolean Insert(String name,String id,String password,String jumin) {
        boolean result=false;
        
        try {
            con=getConnection(ip);
            
            String sql="select jumin from customer where id=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1, id);
            rs=pstmt.executeQuery();
            if(rs.next()) {
                throw new LoginFailException("중복된 아이디입니다.");
            }else {
                sql="INSERT INTO customer VALUES(null,?,?,?,?)";
                pstmt=con.prepareStatement(sql);
                pstmt.setString(1, name);
                pstmt.setString(2, id);
                pstmt.setString(3, password);
                pstmt.setString(4, jumin);
                pstmt.executeUpdate();
                result=true;
                
                
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (LoginFailException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            closeDb();
        }
        return result;
    }
    
    //삭제 작업
    public boolean Delete(int idx) {
        boolean result=false;
        try {
            con=getConnection(ip);
            String sql="DELETE FROM customer WHERE idx=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1, idx);
            pstmt.executeUpdate();
            result=true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            closeDb();
        }
        return result;
    }
    
    //회원목록 불러오기
    public Vector<Vector> select(){
        Vector<Vector> item=new Vector<Vector>();
        
        try {
            con=getConnection(ip);
            String sql="SELECT * FROM customer";
            pstmt=con.prepareStatement(sql);
            rs=pstmt.executeQuery();
            while(rs.next()) {
                Vector rowData=new Vector();
                int idx=rs.getInt("idx");
                String name=rs.getString("name");
                String id=rs.getString("id");
                String password=rs.getString("password");
                String jumin=rs.getString("jumin");
                rowData.add(idx);
                rowData.add(name);
                rowData.add(id);
                rowData.add(password);
                rowData.add(jumin);
                
                item.add(rowData);
            }
            return item;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            closeDb();
        }
        return null;
        
    }
    
    //회원정보 수정
    public boolean update(String name,String id,String password,String jumin,int idx) {
        boolean result=false;
        
        try {
            con=getConnection(ip);
            String sql="UPDATE customer SET name=?,id=?,password=?,jumin=? WHERE idx=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, id);
            pstmt.setString(3, password);
            pstmt.setString(4, jumin);
            pstmt.setInt(5, idx);
            pstmt.executeUpdate();
            result=true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            closeDb();
        }
        
        return result;
    }
}
 
 
 
 
 
 
 
 
cs

 

 

 

버튼들의 주소를 가져와서 e.getsource()로 각 버튼들을 눌렀을 때 각기 다른 기능을 하도록 구현해 보았다.

회원 목록을 뽑아서 각 회원들을 눌렀을 때 왼쪽의 창으로 setText()로 텍스트를 넘겨주고 그걸 수정해서 회원정보 수정을 할 수 있도록 구현해보았다. 크게 어렵진 않으니 잘 읽어보며 다시 복습을 해야겠다.