9일차 Swing02 클래스 (DML 모두 구현, Alert Dialog / 확인창 구현)
2014학년도 겨울 심화학기/JAVA
Written by 긍지높은취객 on 2014. 12. 18. 15:59
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class Swing02 extends JFrame
{
JTextArea ta; //
Swing02()
{
try
{
Class. forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException 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 name = new JTextField(10);
add( name);
add( new JLabel( "학과 : "));
JTextField dept = new JTextField(10);
add( dept);
add( new JLabel( "학번 : "));
JTextField id = new JTextField(10);
add( id);
ta = new JTextArea( "", 20, 30); // 텍스트에어리어 생성
add( new JScrollPane(ta )); // 스크롤 적용
JButton list = new JButton( "목록"); // // 'List'버튼 생성
add( list);
JButton insert = new JButton( "등록"); // 'Insert'버튼 생성
add( insert);
JButton update = new JButton( "수정"); // 'update'버튼 생성
add( update);
JButton delete = new JButton( "삭제"); // 'delete'버튼 생성
add( delete);
JButton search = new JButton( "검색"); // 'search'버튼 생성
add( search);
// ----------------------------------------------------------------------------------
// 익명 클래스 이용 (이벤트 처리) -> 목록 처리
list.addActionListener( new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
List(); // 목록 갱신 메소드 호출
}
});
// 익명 클래스 이용2 (이벤트 처리) -> 등록 처리
insert.addActionListener( new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
Statement stmt = conn.createStatement();
String n = name.getText();
String d = dept.getText();
String i = id.getText();
// insert문 실행
int result = stmt.executeUpdate("insert into student values('"+n+"','"+ d+ "','"+i +"')" );
ta.setText( "");
if( result == 1)
{
// ta.append("Insert Complete!");
List(); // 목록 갱신 메소드 호출
}
conn.close();
}
catch(Exception ex )
{
// System.out.println(ex.getStackTrace());
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
{
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
Statement stmt = conn.createStatement();
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")); // 학과 텍스트필드에 학과 출력
}
rs.close();
conn.close();
}
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
{
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
Statement stmt = conn.createStatement();
String i = id.getText();
String n = name.getText();
String d = dept.getText();
// update문 실행
stmt.executeUpdate( "update student set name='"+n+"', dept='"+ d+ "' where id='"+i +"'" );
ta.setText( ""); // 텍스트에어리어 초기화
ta.setText( "Update Complete!");
JOptionPane.showMessageDialog( null, "Update Complete!", "Complete Dialog", JOptionPane.INFORMATION_MESSAGE );
conn.close();
}
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
{
int result = JOptionPane.showConfirmDialog( null, "Delete?" , "Delete Dialog", JOptionPane.YES_NO_OPTION);
if( result == JOptionPane.YES_OPTION )
{
try
{
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
Statement stmt = conn.createStatement();
String i = id.getText();
// delete문 실행
stmt.executeUpdate( "delete from student where id='"+i+"'");
ta.setText( "");
ta.setText( "Delete Complete!");
JOptionPane.showMessageDialog( null, "Delete Complete!", "Complete Dialog", JOptionPane.INFORMATION_MESSAGE );
conn.close();
}
catch(Exception ex )
{
System. out.println(ex .getStackTrace());
}
}
else if (result == JOptionPane.NO_OPTION )
{
}
}
}
});
// ----------------------------------------------------------------------------------
setResizable( false); // 화면 크기 고정
setSize(350, 500); // 화면 크기 설정
setVisible( true); // 화면 출력 설정
}
public void List()
{
try
{
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
System. out.println("JDBC Connection Complete!");
Statement stmt = conn.createStatement();
// select문 실행
ResultSet rs = stmt.executeQuery( "select * from student"); // SQL문이 rs에 저장된다.
ta.setText( ""); // 텍스트에어리어 초기화
ta.append( "이름\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") + "\n" );
}
rs.close(); // ResultSet을 닫는다.
conn.close(); // Connection을 닫는다. (메모리 자원낭비 방지)
}
catch(Exception ex )
{
System. out.println(ex .getStackTrace());
}
}
public static void main(String [] args)
{
new Swing02(); // 생성자 호출
}
}
'2014학년도 겨울 심화학기 > JAVA' 카테고리의 다른 글
10일차 Student.sql (주소칼럼 추가) (0) | 2014.12.19 |
---|---|
10일차 Swing02 클래스 (JDBC/Statement 연결 구문 위치변경, 주소칼럼 추가, 과제) (0) | 2014.12.19 |
8일차 Swing02 클래스 (이벤트 처리방법 3가지, JFrame, JTextField에 DML 기능 구현 : select, insert) (0) | 2014.12.17 |
7일차 Swing02 클래스 (SQL문 연동 및 DML문 작성 /JFrame, JTextField, JLabel 생성) (0) | 2014.12.16 |
7일차 Student.sql (샘플DB 생성, JAVA와 연동) (0) | 2014.12.16 |