package model1;
public class ZipcodeTO {
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String ri;
private String bunji;
... (getter/ setter) 길어서 생략
2.DB 연결 / 쿼리 정보 가져오는 DAO 클래스 만들기
package model1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class ZipcodeDAO {
private Connection conn = null;
public ZipcodeDAO() {
String url = "jdbc:mariadb://localhost:3306/project";
String user = "project";
String password = "1234";
try {
Class.forName("org.mariadb.jdbc.Driver");
this.conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
System.out.println("[에러] : " + e.getMessage());
} catch (SQLException e) {
System.out.println("[에러] : " + e.getMessage());
}
}
public ArrayList<ZipcodeTO> searchZipcode(String strDong) {
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<ZipcodeTO> addresses = new ArrayList<>();
String sql = "select zipcode, sido, gugun, dong, ri, bunji
from zipcode where dong like ?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, strDong + "%");
rs = pstmt.executeQuery();
while(rs.next()) {
ZipcodeTO to = new ZipcodeTO();
to.setZipcode( rs.getString( "zipcode" ) );
to.setSido( rs.getString( "sido" ) );
to.setGugun( rs.getString( "gugun" ) );
to.setDong( rs.getString( "dong" ) );
to.setRi( rs.getString( "ri" ) );
to.setBunji( rs.getString( "bunji" ));
addresses.add(to);
}
} catch (SQLException e) {
System.out.println("[에러] : " + e.getMessage());
} finally {
if( rs != null ) try { rs.close(); } catch( SQLException e ) {}
if( pstmt != null ) try { pstmt.close(); } catch( SQLException e ) {}
if( conn != null ) try { conn.close(); } catch( SQLException e ) {}
}
return addresses;
}
}
package model1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
public class ZipcodeListModel2 extends AbstractListModel<String> {
private ArrayList<ZipcodeTO> items;
public ZipcodeListModel2(String strDong) {
ZipcodeDAO dao = new ZipcodeDAO();
this.items = dao.searchZipcode(strDong);
}
@Override
public int getSize() {
return items.size();
}
@Override
public String getElementAt(int index) {
ZipcodeTO to = items.get(index); --> 필드가 private 변수므로 to에 넘겨줌
String address = String.format("[%s] %s %s %s %s %s",to.getZipcode(),
to.getSido(), to.getGugun(), to.getDong(), to.getRi(), to.getBunji());
return address;
}
}
JButton btn = new JButton("검색");
btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String strDong = textField.getText().trim();
if(strDong.length() < 2) {
JOptionPane.showMessageDialog(ZipcodeSearchUI01.this,
"동 이름 2자 이상 입력", "에러", JOptionPane.ERROR_MESSAGE);
}
list.setModel(new ZipcodeListModel2(strDong));
}
});
같은 방식으로 밑의 사원 정보 검색기도 만들 수 있다( 복습해보기 )
테이블을 만들어줌
model 통하여 행과 열 만들기, enabled을 통해서 읽기 / 쓰기 모드를 결정 가능
-> 보통 model 안에 editable을 사용하여 읽기 / 쓰기 결정하고 resizalbe로 크기 고정시킨다.
저렇게 하고 실행시키면 위의 컬럼명은 안 뜨는데, table에 scroll 집어넣어야 컬럼명이 뜬다.
원래 GUI에서 만들어진 코드 형식
table.setModel(new DefaultTableModel(
new Object[][] { --> 데이터들
{"1", "2", "3", "4", "5"},
{null, null, null, null, null},
},
new String[] { --> 컬럼 이름
"\uCEEC\uB7FC\uBA851", "\uCEEC\uB7FC\uBA852", "\uCEEC\uB7FC\uBA853",
"\uCEEC\uB7FC\uBA854", "\uCEEC\uB7FC\uBA855"
}
) {
boolean[] columnEditables = new boolean[] {
false, false, false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
} --> boolean 메서드 다 합쳐서 editable 효과
});
getColumnName 메서드 = 컬럼 이름 반환(컬럼 이름 필요할 시, 필수 아님)
-- 3개는 디폴트값 --
getRowCount = 행 수 반환
getColumnCount = 열 수 반환
getValueAt = 주어진 행렬 위치에 저장된 데이터 반환
table.setModel(new CustomTableModel1());
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class CustomTableModel2 extends AbstractTableModel {
//ArrayList<Array List<String>>
//ArrayList<~~To> 이렇게들 많이 씀
private ArrayList<ArrayList<String>> items;
private String[] columnNames = {
"col1", "col2", "col3", "col4", "col5"
};
public String getColumnName(int column) {
// TODO Auto-generated method stub
return columnNames[column];
}
public CustomTableModel2() {
ArrayList<String> item1 = new ArrayList<>();
item1.add("11"); item1.add("12"); item1.add("13"); item1.add("14"); item1.add("15");
ArrayList<String> item2 = new ArrayList<>();
item2.add("21"); item2.add("22"); item2.add("23"); item2.add("24"); item2.add("25");
ArrayList<String> item3 = new ArrayList<>();
item3.add("31"); item3.add("32"); item3.add("33"); item3.add("34"); item3.add("35");
items = new ArrayList<>();
items.add(item1);
items.add(item2);
items.add(item3);
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return items.size();
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return items.get(0).size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
return items.get(rowIndex).get(columnIndex);
}
}
디자인 코드쪽은 위와 동일(클래스명만 바꾸기)
public class TableTO {
private String num1;
private String num2;
private String num3;
private String num4;
private String num5;
...(getter / setter)
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class CustomTableModel3 extends AbstractTableModel {
private ArrayList<TableTO> items;
public CustomTableModel3() {
TableTO to1 = new TableTO();
to1.setNum1("11");
to1.setNum2("12");
to1.setNum3("13");
to1.setNum4("14");
to1.setNum5("15");
TableTO to2 = new TableTO();
to2.setNum1("21");
to2.setNum2("22");
to2.setNum3("23");
to2.setNum4("24");
to2.setNum5("25");
TableTO to3 = new TableTO();
to3.setNum1("31");
to3.setNum2("3");
to3.setNum3("33");
to3.setNum4("34");
to3.setNum5("35");
items = new ArrayList<>();
items.add(to1);
items.add(to2);
items.add(to3);
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return items.size();
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 5; //고정적이기 때문에 개수 써주기
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
String result = "";
TableTO to = items.get(rowIndex);
switch(columnIndex) { // 컬럼 순서에 따라서 각각의 데이터 정보 가져온다
case 0:
result = to.getNum1();
break;
case 1:
result = to.getNum2();
break;
case 2:
result = to.getNum3();
break;
case 3:
result = to.getNum4();
break;
default :
result = to.getNum5();
break;
}
return result;
}
}
public class TableTO {
private String empno;
private String ename;
private String job;
private String mgr;
private String hiredate;
private String sal;
private String comm;
private String deptno;
...(getter / setter)
}
package tablepack;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class TableDAO {
private Connection conn = null;
public TableDAO() {
String url = "jdbc:mariadb://localhost:3306/sample";
String user = "root";
String password = "123456";
try {
Class.forName("org.mariadb.jdbc.Driver");
this.conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
System.out.println("[에러] : " + e.getMessage());
} catch (SQLException e) {
System.out.println("[에러] : " + e.getMessage());
}
}
public ArrayList<TableTO> showSelect() {
PreparedStatement pstmt = null;
ResultSet rs = null;
//전체 데이터를 보여줄 것이기 때문에 매개변수 필요없다.
ArrayList<TableTO> allEmp = new ArrayList<>();
String sql = "select empno, ename, job, mgr, hiredate, sal, comm, deptno from emp";
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
TableTO to = new TableTO();
to.setEmpno(rs.getString("empno"));
to.setEname(rs.getString("ename"));
to.setJob(rs.getString("job"));
to.setMgr(rs.getString("mgr"));
to.setHiredate(rs.getString("hiredate"));
to.setSal(rs.getString("sal"));
to.setComm(rs.getString("comm"));
to.setDeptno(rs.getString("deptno"));
allEmp.add(to);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if( rs != null ) try { rs.close(); } catch( SQLException e ) {}
if( pstmt != null ) try { pstmt.close(); } catch( SQLException e ) {}
if( conn != null ) try { conn.close(); } catch( SQLException e ) {}
}
return allEmp;
}
package tablepack;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class CustomTableModel extends AbstractTableModel {
ArrayList<TableTO> items;
//컬럼명 바꾸기
private String[] columnNames = {
"empno", "ename", "job", "mgr", "hiredate", "sal",
"comm", "deptno"
};
//저장된 emp 정보 가져오기
public CustomTableModel() {
TableDAO dao = new TableDAO();
this.items = dao.showSelect();
}
//컬럼명 반환
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public int getRowCount() {
return items.size();
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
String result = "";
TableTO to = items.get(rowIndex);
//순서 모르니 스위치 통해서 정해주기
switch(columnIndex) { // 컬럼 순서에 따라서 각각의 데이터 정보 가져온다
case 0:
result = to.getEmpno();
break;
case 1:
result = to.getEname();
break;
case 2:
result = to.getJob();
break;
case 3:
result = to.getMgr();
break;
case 4 :
result = to.getHiredate();
break;
case 5 :
result = to.getSal();
break;
case 6 :
result = to.getComm();
break;
default :
result = to.getDeptno();
break;
}
return result;
}
}
table.setModel(new CustomTableModel());
tip : 테이블 또한 이벤트를 통하여 값 출력할 수 있다.
public void mouseClicked(MouseEvent e) {
System.out.println(table.getSelectedRow());
System.out.println(table.getSelectedColumn());
System.out.println(table.getValueAt(table.getSelectedRow(),
table.getSelectedColumn()));
}
getSelectedRow() - 클릭한 행 위치 리턴
getSelectedColumn() - 클릭한 열 위치 리턴
getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
-> 클릭한 행, 열 위치에 있는 값 리턴