관리 메뉴

moozi

haksa table 본문

TIS_2017/응용sw_2기

haksa table

moozi 2017. 7. 24. 09:27

import java.awt.Component;

import java.awt.Container;

import java.awt.Dimension;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.JTextField;

import javax.swing.table.DefaultTableModel;

import javax.swing.table.TableCellRenderer;

import javax.swing.table.TableColumn;

import javax.swing.table.TableColumnModel;


public class Haksa02 extends JFrame {

Container contentPane;

String[] language={"영어","중국어","일본어","기타"};

JTextField tfName;

JTextField tfNo;

JTextField tfDept_ID;

JTextField tfAddress;

Connection conn = null; // 연결객체

    ResultSet rs = null;    // select한 결과 조회.cursor

    Statement stmt = null;  // 쿼리실행객체

    String url = null;   // 연결문자열

    String id = "ora_user";    // 오라클 ID

    String pw = "hong"; // 오라클 PW

    DefaultTableModel model;

JTable table;

//테이블 컬럼 가로크기 자동 조절

public void resizeColumnWidth(JTable table) {

   final TableColumnModel columnModel = table.getColumnModel();

   for (int column = 0; column < table.getColumnCount(); column++) {

       int width = 15; // Min width

       for (int row = 0; row < table.getRowCount(); row++) {

           TableCellRenderer renderer = table.getCellRenderer(row, column);

           Component comp = table.prepareRenderer(renderer, row, column);

           width = Math.max(comp.getPreferredSize().width +1 , width);

       }

       if(width > 300)

           width=300;

       columnModel.getColumn(column).setPreferredWidth(width);

   }

}

Haksa02(){

this.setTitle("학사관리");

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// DB연결 -------------------------------------

// 연결문자열.

        url ="jdbc:oracle:thin:@localhost:1521:orcl";

        // 드라이버 로드

        try{

       Class.forName("oracle.jdbc.driver.OracleDriver");

       

       // 연결

       conn = DriverManager.getConnection(url,id,pw);

       

       System.out.println("연결되었습니다.");

       

       // statement객체 생성

       stmt = conn.createStatement();

        }catch(Exception e){

        e.printStackTrace(); //에러메시지 출력.

        }

// DB연결.끝.----------------------------------

this.contentPane=getContentPane();

this.contentPane.setLayout(new FlowLayout());

this.contentPane.add(new JLabel("이름"));

tfName=new JTextField(10); 

this.contentPane.add(tfName);

this.contentPane.add(new JLabel("학번"));

tfNo=new JTextField(12);

this.contentPane.add(tfNo);

this.contentPane.add(new JLabel("학과"));

tfDept_ID=new JTextField(25);

this.contentPane.add(tfDept_ID);

this.contentPane.add(new JLabel("주소"));

tfAddress=new JTextField(25);

this.contentPane.add(tfAddress);

// this.contentPane.add(new JLabel("외국어"));

// JComboBox cb1=new JComboBox(language);

// cb1.addActionListener(new ActionListener(){

// @Override

// public void actionPerformed(ActionEvent arg0) {

// JComboBox cb=(JComboBox)arg0.getSource();

// System.out.println(cb.getSelectedIndex());

// System.out.println(language[cb.getSelectedIndex()]);

// }});

// this.contentPane.add(cb1);

      // 컬럼명 추가

        String colName[]={"학번","이름","학과","주소"};

model=new DefaultTableModel(colName,0);

table = new JTable(model){

//컬럼사이즈 컨텐츠 길이에 맞게 자동 조절

   @Override

      public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {

          Component component = super.prepareRenderer(renderer, row, column);

          int rendererWidth = component.getPreferredSize().width;

          TableColumn tableColumn = getColumnModel().getColumn(column);

          tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));

          return component;

       }

   };;

// table.getColumn("주소").setPreferredWidth(150);

table.setPreferredScrollableViewportSize(new Dimension(330,200));

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

JScrollPane sp=new JScrollPane(table);

add(sp);


 table.addMouseListener(new MouseListener(){  

  @Override

  public void mouseClicked(MouseEvent e) {

   table=(JTable)e.getComponent();//클릭한 테이블 구하기

   model=(DefaultTableModel)table.getModel();//테이블의 모델 구하기

   String no=(String)model.getValueAt(table.getSelectedRow(), 0);

   tfNo.setText(no);

   String name=(String)model.getValueAt(table.getSelectedRow(), 1);

   tfName.setText(name);

   String dept_id=(String)model.getValueAt(table.getSelectedRow(), 2);

   tfDept_ID.setText(dept_id);

   String address=(String)model.getValueAt(table.getSelectedRow(), 3);

   tfAddress.setText(address);

  }


  public void mouseEntered(MouseEvent e) {}

  public void mouseExited(MouseEvent e) {}

  public void mousePressed(MouseEvent e) {}

  public void mouseReleased(MouseEvent e) {    

  }});





JButton insertBtn=new JButton("입력");

this.contentPane.add(insertBtn);

insertBtn.addActionListener(new ActionListener(){


@Override

public void actionPerformed(ActionEvent arg0) {

       try{

       

           // Insert문 실행

           String sql="insert into student "

            + " values( '"+tfNo.getText()+"' ,"

            + "         '"+tfName.getText()+"' ,"

               + "         '"+tfDept_ID.getText()+"' ,"

               + "         '"+tfAddress.getText()+"')";

           


           stmt.executeUpdate(sql);

           

  

           //stmt.close();

           // conn.close();

  

           //메시지출력

           JOptionPane.showMessageDialog(null, "입력되었습니다", "알림", JOptionPane.INFORMATION_MESSAGE);


       } catch (Exception e){

           e.printStackTrace();

       }


}});

JButton updateBtn=new JButton("수정");

this.contentPane.add(updateBtn);

updateBtn.addActionListener(new ActionListener(){


@Override

public void actionPerformed(ActionEvent arg0) {

try{            

           // Update문 실행

           String sql="update student set "

            + " name='"+tfName.getText()+"' , "

            + " dept_ID='"+tfDept_ID.getText()+"' ,"

            + " address='"+tfAddress.getText()+"' "

            + " where no='"+tfNo.getText()+"'";


           System.out.println(sql);

           

           stmt.executeUpdate(sql);

           

           

  

           //stmt.close();

           // conn.close();

  

           //메시지출력

           JOptionPane.showMessageDialog(null, "수정되었습니다", "알림", JOptionPane.INFORMATION_MESSAGE);


       } catch (Exception e){

           e.printStackTrace();

       }

}});

JButton deleteBtn=new JButton("삭제");

this.contentPane.add(deleteBtn);

deleteBtn.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent arg0) {

try{            

           // Confirm Dialog사용

int result=JOptionPane.showConfirmDialog(null, "삭제하시겠습니까?","삭제",JOptionPane.YES_NO_OPTION);

if(result==JOptionPane.YES_OPTION){

// Delete문 실행

           String sql="delete from student "

            + " where no='"+tfNo.getText()+"'";

           System.out.println(sql);

           

           stmt.executeUpdate(sql);

           

         //메시지출력

           JOptionPane.showMessageDialog(null, "삭제되었습니다", "알림", JOptionPane.INFORMATION_MESSAGE);

}

           

  

           //stmt.close();

           // conn.close();

  

           


       } catch (Exception e){

           e.printStackTrace();

       }

}});

JButton selectBtn=new JButton("목록");

this.contentPane.add(selectBtn);

selectBtn.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent arg0) {

       try{                    // select문 실행

           rs = stmt.executeQuery("select * from student");

                         

//JTable 초기화

model.setNumRows(0);

while(rs.next()){

String[] row=new String[4];//컬럼의 갯수가 4

row[0]=rs.getString("no");

row[1]=rs.getString("name");

row[2]=rs.getString("dept_id");

row[3]=rs.getString("address");

model.addRow(row);

}

  

           rs.close();

          // stmt.close();

          // conn.close();

  


       } catch (Exception a){

           a.printStackTrace();

       }

}});

this.setSize(350,400);

this.setVisible(true);

}


public static void main(String[] args) {

new Haksa02();


}


}



'TIS_2017 > 응용sw_2기' 카테고리의 다른 글

my.ini  (0) 2017.07.24
haksa menu  (0) 2017.07.24
jdbc연습문제02  (0) 2017.07.21
jdbc03 new  (0) 2017.07.21
7/21 haksa new  (0) 2017.07.21
Comments