import java.awt.event.*;

import javax.swing.*;

class MenuActionListener implements ActionListener
{
         @Override
         public void actionPerformed(ActionEvent e)
        {
                String cmd = e.getActionCommand();
                System. out.println(cmd );
        }
}

public class Swing03 extends JFrame
{
        Swing03()
        {
               setTitle( "학사관리 시스템" );
                setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE);
               
                JMenuBar bar = new JMenuBar();
               
                JMenu M_student = new JMenu( "학생관리" ); // 학생관리 메뉴    
                bar.add( M_student); // 학생관리 메뉴 추가
                JMenu M_book = new JMenu( "도서관리" ); // 도서관리 메뉴    
                bar.add( M_book); // 도서관리 메뉴 추가
               
                JMenuItem MI_list = new JMenuItem( "학생목록" ); // 학생목록 세부메뉴
                M_student.add( MI_list); // 학생목록 세부메뉴 추가
                JMenuItem MI_insert = new JMenuItem("학생등록" ); // 학생등록 세부메뉴
                M_student.add( MI_insert); // 학생등록 세부메뉴 추가
                JMenuItem MI_update = new JMenuItem("학생수정" ); // 학생수정 세부메뉴
                M_student.add( MI_update); // 학생수정 세부메뉴 추가
                M_student.addSeparator(); // 구분선 추가
                JMenuItem MI_status = new JMenuItem("학적변경" ); // 학적변경 세부메뉴
                M_student.add( MI_status); // 학적변경 세부메뉴 추가
               
                // 메뉴 아이템 이벤트 처리
                MI_list.addActionListener( new MenuActionListener());
               
               setJMenuBar( bar);
               setSize(800, 600);
               setVisible( true);
        }
        
         public static void main(String [] args)
        {
                new Swing03();
        }
}

10일차 Student.sql (주소칼럼 추가)


2014학년도 겨울 심화학기/JAVA

Written by 긍지높은취객 on 2014. 12. 19. 16:01

 
create database sampledb;

use sampledb;

drop table student;

create table student
(
     name varchar(20) not null, -- 이름
    dept varchar(20) not null, -- 학과
    id char(10) primary key not null, -- 학번, 기본키
    address varchar(50) not null -- 주소
);

insert into student values('최규식', '스마트컨텐츠개발', '2014071023', '강원도 홍천군');
insert into student values('박태수', '스마트컨텐츠기획', '2014072008', '경기도 용인시');
insert into student values('정상혁', '스마트컨텐츠마케팅', '2014071020', '서울시 관악구');

select * from student order by name asc;

 

 
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

import javax.swing.*;


public class Swing02 extends JFrame
{
        
         JTextArea ta; // TextArea. 결과출력창
        Connection conn; // 연결 객체
        Statement stmt;
        
        Swing02()
        {
                try
               {
                        Class. forName("com.mysql.jdbc.Driver");
                        conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" );
                        stmt = conn.createStatement();
               }
                catch (Exception e1 )
               {
                        e1.printStackTrace();
               } // jdbc 드라이버 로드
               
                try
               {
                        UIManager. setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
               }
                catch (Exception e )
               {
                        e.printStackTrace();
               }
               
               setTitle( "학생관리" );
                setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE);
               
               setLayout( new FlowLayout( FlowLayout. LEFT)); // 레이아웃 설정
               
               add( new JLabel( "학번 : "));
                JTextField id = new JTextField(10);
               add( id);

               add( new JLabel( "이름 : "));
                JTextField name = new JTextField(10);
               add( name);
               
               add( new JLabel( "                                                             "));
               
               add( new JLabel( "학과 : "));
                JTextField dept = new JTextField(10);
               add( dept);
               
               add( new JLabel( "                                                                                                                              "));
               
               add( new JLabel( "주소 : "));
                JTextField address = new JTextField(25);
               add( address);
        
                ta = new JTextArea( "", 25, 48); // 텍스트에어리어 생성
               add( new JScrollPane(ta )); // 스크롤 적용
               
                JButton list = new JButton( "목록"); // // 'List'버튼 생성
               add( list);
               add( new JLabel( "        " ));
                JButton insert = new JButton( "등록"); // 'Insert'버튼 생성
               add( insert);
               add( new JLabel( "        " ));
                JButton update = new JButton( "수정"); // 'update'버튼 생성
               add( update);
               add( new JLabel( "        " ));
                JButton delete = new JButton( "삭제"); // 'delete'버튼 생성
               add( delete);
               add( new JLabel( "        " ));
                JButton search = new JButton( "검색"); // 'search'버튼 생성
               add( search);
               add( new JLabel( "        " ));
                JButton out = new JButton( "종료"); // 'out'버튼 생성
               add( out);
               
                // 종료 이벤트 처리
               addWindowListener( new WindowAdapter()
               {
                          public void windowClosing(WindowEvent e)
                          {
                                 try
                                 {
                                         if( conn != null)
                                         {
                                         conn.close();
                                         }
                                 }
                                 catch (SQLException e1 )
                                 {
                                         e1.printStackTrace();
                                 }
                                
                                 JOptionPane.showMessageDialog( null, "Good Bye", "Exit Dialog" , JOptionPane.INFORMATION_MESSAGE );
                          }
               });
               
                // ----------------------------------------------------------------------------------
               
                // 익명 클래스 이용 (이벤트 처리) -> 목록 처리
                list.addActionListener( new ActionListener()
               {
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                              List(); // 목록 갱신 메소드 호출
                       }
               });
               
                // 익명 클래스 이용2 (이벤트 처리) -> 등록 처리
                insert.addActionListener( new ActionListener()
               {      
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                               try
                              {
                                       String n = name.getText();
                                       String d = dept.getText();
                                       String i = id.getText();
                                       String a = address.getText();
                                      
                                       // insert문 실행
                                       int result = stmt.executeUpdate("insert into student values('"+n+"','"+ d+ "','"+i +"','" +a +"')" );
                                      
                                       ta.setText( "");
                                       if( result == 1)
                                      {
                                             List(); // 목록 갱신 메소드 호출
                                      }
                              }
                               catch(Exception ex )
                              {      
                                       System. out.println(ex .getMessage());
                              }
                       }
               });
               
                // 익명 클래스 이용3 (이벤트 처리) -> 검색 처리
                search.addActionListener( new ActionListener()
               {
                       
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                              
                               if(( id.getText()).equals( ""))
                              {
                                       JOptionPane.showMessageDialog( null, "No ID in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else
                              {
                                       try
                                      {
                                              String i = id.getText();

                                              // select문 실행
                                             ResultSet rs = stmt.executeQuery("select * from student where id='"+i+"'");
                                             
                                              ta.setText( ""); // 텍스트에어리어 초기화
                                             
                                              ta.append( "이름\t");
                                              ta.append( "학과\t\t");
                                              ta.append( "학번\n");
                                               ta.append( "============================================\n" );
                                             
                                              if( rs.next())
                                             {
                                                      ta.append( rs.getString( "name") + "\t" ); // 검색한 이름을 텍스트에어리어에 출력
                                                      ta.append( rs.getString( "dept") + "\t" ); // 검색한 학과을 텍스트에어리어에 출력
                                                      ta.append( rs.getString( "id") + "\n" ); // 검색한 학번을 텍스트에어리어에 출력
                                                     
                                                      id.setText( rs.getString( "id")); // 학번 텍스트필드에 학번 출력
                                                      name.setText( rs.getString( "name")); // 이름 텍스트필드에 이름 출력
                                                      dept.setText( rs.getString( "dept")); // 학과 텍스트필드에 학과 출력
                                             }
                                      }
                                       catch(Exception ex )
                                      {      
                                               System. out.println(ex .getStackTrace());
                                      }
                              }             
                       }             
               });
               
                // 익명 클래스 이용4 (이벤트처리) -> 수정 처리
                update.addActionListener( new ActionListener()
               {
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                               if(( id.getText()).equals( ""))
                              {
                                       JOptionPane.showMessageDialog( null, "No ID in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else
                              {
                                       int result = JOptionPane.showConfirmDialog( null, "Update?" , "Update Dialog", JOptionPane.YES_NO_OPTION);
                                      
                                       if( result == JOptionPane.YES_OPTION )
                                      {
                                              try
                                             {
                                                      String i = id.getText();
                                                      String n = name.getText();
                                                      String d = dept.getText();
                                                      String a = address.getText();
        
                                                      // update문 실행
                                                      stmt.executeUpdate( "update student set name='"+n+"', dept='"+ d+ "', address='"+a +"' where id='"+i+"'");
                                                     
                                                      ta.setText( ""); // 텍스트에어리어 초기화                              
                                                     
                                                     List(); // 목록 갱신 메소드 호출
                                                     
                                                      JOptionPane.showMessageDialog( null, "Update Complete!", "Complete Dialog", JOptionPane.INFORMATION_MESSAGE );
               
                                             }
                                              catch(Exception ex )
                                             {      
                                                      System. out.println(ex .getMessage());
                                             }
                                      }
                                       else if (result == JOptionPane.NO_OPTION )
                                      {
                                             
                                      }
                              }
                       }
               });
               
                // 익명 클래스 이용5 (이벤트 처리) -> 삭제 처리
                delete.addActionListener( new ActionListener()
               {
                       
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                              
                               if(( id.getText()).equals( ""))
                              {
                                       JOptionPane.showMessageDialog( null, "No ID in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else if ((dept .getText()).equals(""))
                              {
                                       JOptionPane.showMessageDialog( null, "No Dept in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else if ((name .getText()).equals(""))
                              {
                                       JOptionPane.showMessageDialog( null, "No Name in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else if ((address .getText()).equals(""))
                              {
                                       JOptionPane.showMessageDialog( null, "No address in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else
                              {
                                       int result = JOptionPane.showConfirmDialog( null, "Delete?" , "Delete Dialog", JOptionPane.YES_NO_OPTION);
                                      
                                       if( result == JOptionPane.YES_OPTION )
                                      {
                                              try
                                             {
                                                      String i = id.getText();
                                                     
                                                      // delete문 실행
                                                      stmt.executeUpdate( "delete from student where id='"+i+"'");
                                                     
                                                      ta.setText( "");
                                                     
                                                            List(); // 목록 갱신 메소드 호출

                                                      JOptionPane.showMessageDialog( null, "Delete Complete!", "Complete Dialog", JOptionPane.INFORMATION_MESSAGE );

                                             }
                                              catch(Exception ex )
                                             {      
                                                      System. out.println(ex .getStackTrace());
                                             }
                                      }
                                       else if (result == JOptionPane.NO_OPTION )
                                      {
                                             
                                      }
                              }                     
                       }
               });
               
                // 익명 클래스 이용6 (이벤트 처리) -> 종료 처리
                out.addActionListener( new ActionListener()
               {      
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                               try
                                 {
                                         if( conn != null)
                                         {
                                         conn.close();
                                         }
                                 }
                                 catch (SQLException e1 )
                                 {
                                         e1.printStackTrace();
                                 }
                                
                                 JOptionPane.showMessageDialog( null, "Good Bye", "Exit Dialog" , JOptionPane.INFORMATION_MESSAGE );
                                 dispose();
                       }
               });
               
                // ----------------------------------------------------------------------------------
               
               setResizable( false); // 화면 크기 고정
               setSize(550, 620); // 화면 크기 설정
               setVisible( true); // 화면 출력 설정
        }
        
         public void List()
        {
                try
               {
                        System. out.println("JDBC Connection Complete!");
                       
                        // select문 실행
                       ResultSet rs = stmt.executeQuery( "select * from student"); // SQL문이 rs에 저장된다.
                       
                        ta.setText( ""); // 텍스트에어리어 초기화
                       
                        ta.append( "이름\t");
                        ta.append( "학과\t\t");
                        ta.append( "학번\t\t");
                        ta.append( "주소\n");
                        ta.append( "===========================================================================\n" );
                       
                        while(rs .next())
                       {
                               ta.append( rs.getString( "name") + "\t" );
                               ta.append( rs.getString( "dept") + "\t" );
                               ta.append( rs.getString( "id") + "\t\t" );
                               ta.append( rs.getString( "address") + "\n");
                       }
                        rs.close(); // ResultSet을 닫는다.
               }
                catch(Exception ex )
               {      
                        System. out.println(ex .getStackTrace());
               }
        }
        
         public static void main(String [] args)
        {
                new Swing02(); // 생성자 호출 
        }
}