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(); // 생성자 호출
}
}