관리 메뉴

moozi

Swing Table 본문

카테고리 없음

Swing Table

moozi 2015. 5. 28. 14:02

package swing02;

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

import javax.swing.*;
import javax.swing.table.*;


public class swing02 extends JFrame {
 Connection conn;//연결객체
 
 Statement stmt;
 DefaultTableModel model;
 JTable table;
 
 swing02(){
  //jdbc드라이버 로드
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledb", "root", "1234");
   stmt=conn.createStatement();
  } catch (Exception e2) {   
   e2.printStackTrace();
  }
  
  setTitle("학생관리");
  
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//x버튼 누르면 프로그램 종료
  
  setLayout(new FlowLayout(FlowLayout.LEFT));//레이아웃설정
  
  add(new JLabel("학번"));
  final JTextField TF_id = new JTextField(13);
  add(TF_id);
  
  add(new JLabel("이름"));
  final JTextField TF_name = new JTextField(23);
  add(TF_name);
  
  add(new JLabel("학과"));
  final JTextField TF_dept= new JTextField(40);
  add(TF_dept);
  
  String colName[]={"학번","이름","학과"};
  model=new DefaultTableModel(colName,0);
  table = new JTable(model);
  table.setPreferredScrollableViewportSize(new Dimension(470,200));
  add(table);
  add(new JScrollPane(table));
  
  JButton ListButton=new JButton("목록");
  add(ListButton);
  JButton InsertButton=new JButton("등록");
  add(InsertButton);
  JButton UpdateButton=new JButton("수정");
  add(UpdateButton);  
  JButton DeleteButton=new JButton("삭제");
  add(DeleteButton);  
  JButton SearchButton=new JButton("검색");
  add(SearchButton);
  
  //종료이벤트 처리
  addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    try {
     if(conn!=null){
      conn.close();
     }
    } catch (SQLException e1) {
     
     e1.printStackTrace();
    }
   }
  });
  
  table.addMouseListener(new MouseListener(){

   @Override
   public void mouseClicked(MouseEvent e) {
    table=(JTable)e.getComponent();//클릭한 테이블 구하기
    model=(DefaultTableModel)table.getModel();//테이블의 모델 구하기
    String id=(String)model.getValueAt(table.getSelectedRow(), 0);
    TF_id.setText(id);
    String name=(String)model.getValueAt(table.getSelectedRow(), 1);
    TF_name.setText(name);
    String dept=(String)model.getValueAt(table.getSelectedRow(), 2);
    TF_dept.setText(dept);
    
   }

   public void mouseEntered(MouseEvent e) {}
   public void mouseExited(MouseEvent e) {}
   public void mousePressed(MouseEvent e) {}
   public void mouseReleased(MouseEvent e) {    
   }});
  
  
  
  //목록버튼 이벤트 처리  
  ListButton.addActionListener(new ActionListener(){

   @Override
   public void actionPerformed(ActionEvent e) {
    list();//목록출력   
   }});
  
  //등록버튼 이벤트 처리
  InsertButton.addActionListener(new ActionListener(){

   @Override
   public void actionPerformed(ActionEvent e) {
    if((TF_id.getText()).equals("")){
     JOptionPane.showMessageDialog(null, "학번을 입력하세요!", "알림", JOptionPane.INFORMATION_MESSAGE);
     return; //함수종료
    }
    
    if((TF_name.getText()).equals("")){
     JOptionPane.showMessageDialog(null, "이름을 입력하세요!", "알림", JOptionPane.INFORMATION_MESSAGE);
     return; //함수종료
    }
    
    if((TF_dept.getText()).equals("")){
     JOptionPane.showMessageDialog(null, "학과를 입력하세요!", "알림", JOptionPane.INFORMATION_MESSAGE);
     return; //함수종료
    }
    
    try{
     
     String name=TF_name.getText();
     String dept=TF_dept.getText();
     String id=TF_id.getText();
     
       
     // Insert문 실행
     int result=stmt.executeUpdate("insert into student values('"+name+"','"+dept+"','"+id+"')");
     
    
     if(result==1){
      JOptionPane.showMessageDialog(null, "등록되었습니다!", "알림", JOptionPane.INFORMATION_MESSAGE);
      list();//목록갱신
     }
     
    }
    catch(Exception e1){
     //e.getStackTrace();
     System.out.println(e1.getMessage());
    }
    
    
   }});
  
  //검색버튼 이벤트 처리
  SearchButton.addActionListener(new ActionListener(){

   @Override
   public void actionPerformed(ActionEvent e) {
    if((TF_id.getText()).equals("")){
     JOptionPane.showMessageDialog(null, "학번을 입력하세요!", "알림", JOptionPane.INFORMATION_MESSAGE);
     return; //함수종료
    }
    try{
             
     String id=TF_id.getText();
     
     // Select문 실행
     ResultSet rs=stmt.executeQuery("select * from student where id='"+id+"'");
     
     //JTable 초기화
     model.setNumRows(0);     
     if(rs.next()){            
      TF_id.setText(rs.getString("id"));
      TF_name.setText(rs.getString("name"));
      TF_dept.setText(rs.getString("dept"));
      
      String[] row=new String[3];//컬럼의 갯수가 3
      row[0]=rs.getString("id");
      row[1]=rs.getString("name");
      row[2]=rs.getString("dept");
      model.addRow(row);
     }
     rs.close();
     
    }
    catch(Exception e1){
     //e.getStackTrace();
     System.out.println(e1.getMessage());
    }
    
   }});
  
  //수정버튼 이벤트 처리
  UpdateButton.addActionListener(new ActionListener(){

   @Override
   public void actionPerformed(ActionEvent e) {
    
    if((TF_id.getText()).equals("")){
     JOptionPane.showMessageDialog(null, "학번을 입력하세요!", "알림", JOptionPane.INFORMATION_MESSAGE);
     return; //함수종료
    }
    
    
    int result=JOptionPane.showConfirmDialog(null, "수정하시겠습니까?", "수정", JOptionPane.YES_NO_OPTION);
    if(result==JOptionPane.YES_OPTION){
     try{
              
      String id=TF_id.getText();
      String name=TF_name.getText();
      String dept=TF_dept.getText();
      // update문 실행
      stmt.executeUpdate("update student set name='"+name+"', dept='"+dept+"' where id='"+id+"'");
           
      JOptionPane.showMessageDialog(null, "수정되었습니다!", "알림", JOptionPane.INFORMATION_MESSAGE);
      list();//목록갱신
      
      
     }
     catch(Exception e1){
      //e.getStackTrace();
      System.out.println(e1.getMessage());
     }
    }
   }});
  
  
  //삭제버튼 이벤트 처리
  DeleteButton.addActionListener(new ActionListener(){

   @Override
   public void actionPerformed(ActionEvent e) {
    if((TF_id.getText()).equals("")){
     JOptionPane.showMessageDialog(null, "학번을 입력하세요!", "알림", JOptionPane.INFORMATION_MESSAGE);
     return; //함수종료
    }
    
    
    int result=JOptionPane.showConfirmDialog(null, "삭제하시겠습니까?", "삭제", JOptionPane.YES_NO_OPTION);
    //Yes를 누르면 삭제
    if(result==JOptionPane.YES_OPTION){
     try{
               
      String id=TF_id.getText();
      // delete문 실행
      int result2=stmt.executeUpdate("delete from student where id='"+id+"'");
      if(result2==1){
       list();//목록갱신
       TF_id.setText("");
       TF_name.setText("");
       TF_dept.setText("");
       JOptionPane.showMessageDialog(null, "삭제되었습니다!", "알림", JOptionPane.INFORMATION_MESSAGE);
      }
      
     }
     catch(Exception e1){
      //e.getStackTrace();
      System.out.println(e1.getMessage());
     }
     
    }
    
    
    
    
   }});
  
  setResizable(false);//화면크기고정
  setSize(490, 400);//화면크기
  setVisible(true);
 }
 
 
 public void list(){
  try{
   System.out.println("연결되었습니다.....");
           
   // Select문 실행
   ResultSet rs=stmt.executeQuery("select * from student");
   
   //JTable 초기화
   model.setNumRows(0);
   
   while(rs.next()){
    String[] row=new String[3];//컬럼의 갯수가 3
    row[0]=rs.getString("id");
    row[1]=rs.getString("name");
    row[2]=rs.getString("dept");
    model.addRow(row);
   }
   rs.close();
   
  }
  catch(Exception e1){
   //e.getStackTrace();
   System.out.println(e1.getMessage());
  }
 }
 
 public static void main(String args[]){
  new swing02();//생성자호출
 }
}

Comments