DAO와 DTO 사용 / Swing - 테이블 구조 만들기

준동이·2023년 4월 10일
0
post-custom-banner

문제 풀이

UI 부분

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.border.TitledBorder;

import model1.ZipcodeListModel;

import javax.swing.UIManager;
import java.awt.Color;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractListModel;

public class ZipcodeSearchUI02 extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private JList list;
	private JTextField textField1;
	private JTextField textField2;
	private JButton btn;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ZipcodeSearchUI02 frame = new ZipcodeSearchUI02();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ZipcodeSearchUI02() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 650, 540);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
				"\uC6B0\uD3B8\uBC88\uD638\uAC80\uC0C9\uAE30", TitledBorder.LEADING, TitledBorder.TOP, null,
				new Color(0, 0, 0)));
		panel.setBounds(6, 21, 616, 73);
		contentPane.add(panel);
		panel.setLayout(null);

		JLabel lbl = new JLabel("동이름");
		lbl.setBounds(12, 41, 57, 15);
		panel.add(lbl);

		textField = new JTextField();
		textField.setBounds(67, 38, 428, 21);
		panel.add(textField);
		textField.setColumns(10);

		btn = new JButton("검색");
		btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// 1. 데이터베이스 접속
				// 2. 모델 만들고
				// 3. List
				
				//데이터를 검사하는 루틴
				String strDong = textField.getText().trim();
				if(strDong.length() < 2) {
					JOptionPane.showMessageDialog( ZipcodeSearchUI02.this, "동이름을 2자 이상 입력,", "입력 경고", JOptionPane.WARNING_MESSAGE);
				} else {
					list.setModel(new ZipcodeListModel(strDong));
				}
			}
		});
		btn.setBounds(507, 37, 97, 23);
		panel.add(btn);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setBounds(10, 111, 612, 318);
		contentPane.add(scrollPane);

		list = new JList();
		list.setModel(new AbstractListModel() {
			String[] values = new String[] { "[우편번호] 시도 구군 동 리 번지", "[우편번호] 시도 구군 동 리 번지", "[우편번호] 시도 구군 동 리 번지" };

			public int getSize() {
				return values.length;
			}

			public Object getElementAt(int index) {
				return values[index];
			}
		});
		list.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				textField1.setText((String) list.getSelectedValue());
			}
		});
		scrollPane.setViewportView(list);

		textField1 = new JTextField();
		textField1.setEditable(false);
		textField1.setText("기본주소");
		textField1.setBounds(6, 439, 616, 21);
		contentPane.add(textField1);
		textField1.setColumns(10);

		textField2 = new JTextField();
		textField2.setText("상세주소");
		textField2.setBounds(6, 470, 616, 21);
		contentPane.add(textField2);
		textField2.setColumns(10);
	}
}


클래스

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 ZipcodeListModel extends AbstractListModel<String> {
	// 검색된 우편번호가 저장될 저장소
	private ArrayList<String> items = new ArrayList<>();

	public ZipcodeListModel(String strDong) {
		// TODO Auto-generated constructor stub
		
		// 데이터베이스 연걸
		String url = "jdbc:mysql://localhost:3306/project";
		String user = "project";
		String password = "1234";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			
			Class.forName("org.mariadb.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			String sql = "select zipcode, sido, gugun, dong, ri, bunji from zipcode where dong like ?;";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, strDong + "%");
			
			rs = pstmt.executeQuery();
			while(rs.next()) {
				String zipcode = rs.getString("zipcode");
				String sido = rs.getString("sido");
				String gugun = rs.getString("gugun");
				String dong = rs.getString("dong");
				String ri = rs.getString("ri");
				String bunji = rs.getString("bunji");
				
				String address = String.format("[%s] %s %s %s %s %s", zipcode, sido, gugun, dong, ri, bunji);
				items.add(address + System.lineSeparator());
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			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) {}
		}
				
		
	}

	@Override
	public int getSize() {
		// TODO Auto-generated method stub
		return items.size();
	}

	@Override
	public String getElementAt(int index) {
		// TODO Auto-generated method stub
		return items.get(index);
	}

}



DAO 와 TO 만들어서 분리

TO 클래스 - 데이터 전송 객체

package model1;

public class ZipcodeTO {
	private String zipcode;
	private String sido;
	private String gugun;
	private String dong;
	private String ri;
	private String bunji;
	
	
	
	public String getZipcode() {
		return zipcode;
	}
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}
	public String getSido() {
		return sido;
	}
	public void setSido(String sido) {
		this.sido = sido;
	}
	public String getGugun() {
		return gugun;
	}
	public void setGugun(String gugun) {
		this.gugun = gugun;
	}
	public String getDong() {
		return dong;
	}
	public void setDong(String dong) {
		this.dong = dong;
	}
	public String getRi() {
		return ri;
	}
	public void setRi(String ri) {
		this.ri = ri;
	}
	public String getBunji() {
		return bunji;
	}
	public void setBunji(String bunji) {
		this.bunji = bunji;
	}
	
	
}

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;

//DAO 기본 구성
// 데이터베이스가 여러개면 DAO가 여러 개로 생성하여 사용한다.
public class ZipcodeDAO {
	private Connection conn = null;

	public ZipcodeDAO() {
		// TODO Auto-generated constructor stub
		String url = "jdbc:mysql://localhost:3306/project";
		String user = "project";
		String password = "1234";

		try {
			Class.forName("org.mariadb.jdbc.Driver");
			// this가 Connection conn을 가르킨다
			this.conn = DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} // finally 안써줌
	}

	public ArrayList<ZipcodeTO> searchZipcode(String strDong) {
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		ArrayList<ZipcodeTO> addresses = new ArrayList<>();
		try {
			String sql = "select zipcode, sido, gugun, dong, ri, bunji from zipcode where dong like ?;";
			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) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException e1) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (SQLException e1) {
				}
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e1) {
				}
		}

		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 ZipcodeListModel02 extends AbstractListModel<String> {
	// 검색된 우편번호가 저장될 저장소
	private ArrayList<ZipcodeTO> items;

	public ZipcodeListModel02(String strDong) {
		// TODO Auto-generated constructor stub
		// 생성하는 순간 connection 연결
		ZipcodeDAO dao = new ZipcodeDAO();
		this.items = dao.searchZipcode(strDong);
	}

	@Override
	public int getSize() {
		// TODO Auto-generated method stub
		return items.size();
	}

	@Override
	public String getElementAt(int index) {
		// TODO Auto-generated method stub
		ZipcodeTO to = items.get(index);
		String address = String.format("[%s] %s %s %s %s %s",
										to.getZipcode(), to.getSido(), to.getGugun(),
										to.getDong(), to.getRi(), to.getBunji());
		
		return address;
	}

}

UI 클래스에서 바꿔줌

btn = new JButton("검색");
		btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// 1. 데이터베이스 접속
				// 2. 모델 만들고
				// 3. List
				
				//데이터를 검사하는 루틴
				String strDong = textField.getText().trim();
				if(strDong.length() < 2) {
					JOptionPane.showMessageDialog( ZipcodeSearchUI02.this, "동이름을 2자 이상 입력,", "입력 경고", JOptionPane.WARNING_MESSAGE);
				} else {
                	// ZipcodeListModel02로 바꿔줌
					list.setModel(new ZipcodeListModel02(strDong));
				}
			}
		});



문제 - 사원이름 검색하여 정보 출력

DTO


public class EmpTO {
	private String empno;
	private String ename;
	private String deptno;
	private String sal;
	private String hiredate;
	private String job;
	public String getEmpno() {
		return empno;
	}
	public void setEmpno(String empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getDeptno() {
		return deptno;
	}
	public void setDeptno(String deptno) {
		this.deptno = deptno;
	}
	public String getSal() {
		return sal;
	}
	public void setSal(String sal) {
		this.sal = sal;
	}
	public String getHiredate() {
		return hiredate;
	}
	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	
	
}

DAO

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 EmpDAO {
	Connection conn = null;

	public EmpDAO() {
		// TODO Auto-generated constructor stub
		String url = "jdbc:mysql://localhost:3306/sample";
		String user = "root";
		String password = "123456";

		try {
			Class.forName("org.mariadb.jdbc.Driver");
			// this가 Connection conn을 가르킨다
			this.conn = DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		}
	}
	
	public ArrayList<EmpTO> serarchEmp(String ename) {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		ArrayList<EmpTO> emp = new ArrayList<>();
		try {
			String sql = "select empno, ename, deptno, sal, hiredate, job from emp where ename like ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, ename + "%");
			
			rs = pstmt.executeQuery();
			while(rs.next()) {
				EmpTO to = new EmpTO();
				to.setEmpno(rs.getString("empno"));
				to.setEname(rs.getString("ename"));
				to.setDeptno(rs.getString("deptno"));
				to.setSal(rs.getString("sal"));
				to.setHiredate(rs.getString("hiredate"));
				to.setJob(rs.getString("job"));
				
				emp.add(to);
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if (rs != null)try {rs.close();} catch (SQLException e1) {}
			if (pstmt != null)try {pstmt.close();} catch (SQLException e1) {}
			if (conn != null)try {conn.close();} catch (SQLException e1) {}
		}
		
		return emp;
		
	}
}

클래스

import java.util.ArrayList;

import javax.swing.AbstractListModel;

public class EmpSearchUI extends AbstractListModel<String> {
	
	ArrayList<EmpTO> items;
	
	public EmpSearchUI(String ename) {
		// TODO Auto-generated constructor stub
		EmpDAO dao = new EmpDAO();
		this.items = dao.serarchEmp(ename);
	}
	@Override
	public int getSize() {
		// TODO Auto-generated method stub
		return items.size();
	}
	
	@Override
	public String getElementAt(int index) {
		// TODO Auto-generated method stub
		EmpTO to = items.get(index);
		String name = String.format("[%s] %s %s %s %s %s", 
				to.getEmpno(), to.getEname(), to.getDeptno(), to.getSal(),
				to.getHiredate(), to.getJob());
		
		return name;
		
	}
	
}

UI



import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

public class EmpSearchUI01 extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private JList list;
	private JTextField textField1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					EmpSearchUI01 frame = new EmpSearchUI01();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public EmpSearchUI01() {
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 650, 509);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(255, 255, 255), new Color(160, 160, 160)), "\uC0AC\uC6D0\uC774\uB984 \uAC80\uC0C9\uAE30", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel.setBounds(6, 21, 616, 73);
		contentPane.add(panel);
		panel.setLayout(null);
		
		JLabel lbl = new JLabel("사원이름");
		lbl.setBounds(12, 41, 57, 15);
		panel.add(lbl);
		
		textField = new JTextField();
		textField.setBounds(67, 38, 428, 21);
		panel.add(textField);
		textField.setColumns(10);
		
		JButton btn = new JButton("검색");
		btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				String name = textField.getText().trim();
				if(name.length() < 2) {
					JOptionPane.showMessageDialog(EmpSearchUI01.this, "이름 2글자 이상 입력.", "입력 경고", JOptionPane.WARNING_MESSAGE);
				} else {
					list.setModel(new EmpSearchUI(name));
				}
			}
		});
		btn.setBounds(507, 37, 97, 23);
		panel.add(btn);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setBounds(10, 111, 612, 318);
		contentPane.add(scrollPane);
		
		list = new JList();
		list.setModel(new AbstractListModel() {
			String[] values = new String[] {"[사원번호] 사원이름 부서번호 급여 입사일자 매니저명"};
			public int getSize() {
				return values.length;
			}
			public Object getElementAt(int index) {
				return values[index];
			}
		});
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
			}
		});
		scrollPane.setViewportView(list);
		
		textField1 = new JTextField();
		textField1.setEditable(false);
		textField1.setText("사원정보");
		textField1.setBounds(6, 439, 616, 21);
		contentPane.add(textField1);
		textField1.setColumns(10);
	}
}



스윙으로 테이블 구조 만들기



행과 열 만들어주기
모델에서 만들어준다



이런식으로 만들어 진다. / 입력도 가능하다. / 엑셀 / read only의 엑셀개념



라인 설정



컬럼명은 컬럼명부분이아닌 그 밑에를 눌러서 title란에 입력해주면 된다.



밑에 체크표시 해제하면 읽기전용, 사이즈 조절 불가



외부적으로 뽑아서 쓰기

데이터를 쓰고 읽는 방법이 있는 클래스를 생성
클래스 생성 - > AbstractTableModel 상속

import javax.swing.table.AbstractTableModel;

// 데이터 쓰고
public class CustomTableModel1 extends AbstractTableModel {
	private String[][] items = new String[][] {
		{"11", "12", "13", "14", "15"},
		{"21", "22", "23", "24", "25"},
		{"31", "32", "33", "34", "35"},
		{null, null, null, null, null}
	};
	
	
	// 데이터 읽는방법들
	@Override
	public int getRowCount() {
		// TODO Auto-generated method stub
		return items.length;
	}

	@Override
	public int getColumnCount() {
		// TODO Auto-generated method stub
		return items[0].length;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		// TODO Auto-generated method stub
		return  items[rowIndex][columnIndex];
	}

}

UI

	public JTableEx01() {
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 800, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(12, 10, 495, 277);
		contentPane.add(scrollPane);
		
		table = new JTable();
		scrollPane.setViewportView(table);
		/*
		// 행과 열이 있어서 2차배열이다.
		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\uBA853", "\uCEEC\uB834\uBA855"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		*/
		
		table.setModel(new CustomTableModel1());
		
		table.getColumnModel().getColumn(0).setResizable(false);
		table.getColumnModel().getColumn(1).setResizable(false);
		table.getColumnModel().getColumn(2).setResizable(false);
		table.getColumnModel().getColumn(3).setResizable(false);
		table.getColumnModel().getColumn(4).setResizable(false);
	}



컬럼이름 넣기
위의 코드 외부 클래스에서 컬럼이름 지정 코드, 컬럼이름 읽기 코드 추가

import javax.swing.table.AbstractTableModel;

// 데이터 쓰고
public class CustomTableModel1 extends AbstractTableModel {
	private String[][] items = new String[][] {
		{"11", "12", "13", "14", "15"},
		{"21", "22", "23", "24", "25"},
		{"31", "32", "33", "34", "35"},
		{null, null, null, null, null}
	};
	
	// 컬럼 이름 지정
	private String[] columnNames = {
			"col1", "col2", "com3", "col4", "col5"
	};
	
	// 컬럼 이름 읽는방법 / 적용 시키기 : getColumnName 오버라이딩
	@Override
	public String getColumnName(int column) {
		// TODO Auto-generated method stub
		return columnNames[column];
	}
	
	// 데이터 읽는방법들
	@Override
	public int getRowCount() {
		// TODO Auto-generated method stub
		return items.length;
	}

	@Override
	public int getColumnCount() {
		// TODO Auto-generated method stub
		return items[0].length;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		// TODO Auto-generated method stub
		return  items[rowIndex][columnIndex];
	}

}

후 실행



2차 배열의 다른 표기법

ArrayList

ArrayList<ArrayList<String>> 선언해서 직접 데이터 넣기


import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

public class CustomTableModel2 extends AbstractTableModel {
	private ArrayList<ArrayList<String>> items;
	
	public CustomTableModel2() {
		// TODO Auto-generated constructor stub
        // 아직 객체 생성을 해주지않았기때문에 뒤에 꼭 해줘야한다.
		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);
	}

}



TO로 집어넣기

TO 클래스 생성


public class DataTO {
	private String num1;
	private String num2;
	private String num3;
	private String num4;
	private String num5;
	public String getNum1() {
		return num1;
	}
	public void setNum1(String num1) {
		this.num1 = num1;
	}
	public String getNum2() {
		return num2;
	}
	public void setNum2(String num2) {
		this.num2 = num2;
	}
	public String getNum3() {
		return num3;
	}
	public void setNum3(String num3) {
		this.num3 = num3;
	}
	public String getNum4() {
		return num4;
	}
	public void setNum4(String num4) {
		this.num4 = num4;
	}
	public String getNum5() {
		return num5;
	}
	public void setNum5(String num5) {
		this.num5 = num5;
	}
	
	
}

CustomTable 클래스

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

public class CustomTableModel3 extends AbstractTableModel {
	private ArrayList<DataTO> items;
	
	public CustomTableModel3() {
		// TODO Auto-generated constructor stub
		DataTO to1 = new DataTO();
		to1.setNum1("11");
		to1.setNum2("12");
		to1.setNum3("13");
		to1.setNum4("14");
		to1.setNum5("15");
		
		DataTO to2 = new DataTO();
		to2.setNum1("21");
		to2.setNum2("22");
		to2.setNum3("23");
		to2.setNum4("24");
		to2.setNum5("25");
		
		DataTO to3 = new DataTO();
		to3.setNum1("31");
		to3.setNum2("32");
		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 = "";
		
		DataTO 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();
		}
		
		return result;
	}

}



emp 테이블 넣기

테이블 모델 클래스 - EmpTableModel클래스 생성 -> AbstractTableModel
데이터 - emp

데이터와 연결 - EmpDAO
empDAO()
ArrayList<EmpTO> listEmp()

TO

package pack1;

public class EmpTO {
	private String empno;
	private String ename;
	private String job;
	private String mgr;
	private String hiredate;
	private String sal;
	private String comm;
	private String deptno;
	
	
	public String getEmpno() {
		return empno;
	}
	public void setEmpno(String empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public String getMgr() {
		return mgr;
	}
	public void setMgr(String mgr) {
		this.mgr = mgr;
	}
	public String getHiredate() {
		return hiredate;
	}
	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
	public String getSal() {
		return sal;
	}
	public void setSal(String sal) {
		this.sal = sal;
	}
	public String getComm() {
		return comm;
	}
	public void setComm(String comm) {
		this.comm = comm;
	}
	public String getDeptno() {
		return deptno;
	}
	public void setDeptno(String deptno) {
		this.deptno = deptno;
	}
	
	
}

DAO

package pack1;

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 EmpDAO {
	private Connection conn = null;

	public EmpDAO() {
		// TODO Auto-generated constructor stub
		String url = "jdbc:mysql://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) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		}
	}

	public ArrayList<EmpTO> listEmp() {
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		ArrayList<EmpTO> items = new ArrayList<>();
		try {
			String sql = "select empno, ename, job, mgr, hiredate, sal, comm, deptno from emp";
			pstmt = this.conn.prepareStatement(sql);

			rs = pstmt.executeQuery();
			while (rs.next()) {
				EmpTO to = new EmpTO();
				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"));

				items.add(to);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException e1) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (SQLException e1) {
				}
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e1) {
				}
		}

		return null;
	}
}

커스텀 클래스

package pack1;

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

public class EmpTableModel extends AbstractTableModel {
	private ArrayList<EmpTO> items = new ArrayList<>();
	
	private String[] columnNames = new String[] {
			"empno", "ename", "job", "mgr", "hiredate", "sal", "comm", "deptno"
	};

	public EmpTableModel() {
		// TODO Auto-generated constructor stub
		EmpDAO dao = new EmpDAO();
		items = dao.listEmp();
	}

	@Override
	public int getRowCount() {
		// TODO Auto-generated method stub
		return items.size();
	}

	@Override
	public int getColumnCount() {
		// TODO Auto-generated method stub
		return 8;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		// TODO Auto-generated method stub
		String result = "";
		EmpTO 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();
		}
		
		
		return result;
	}
	
	public String getColumnName(int column) {
		return columnNames[column];
	}

}

UI

package pack1;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;

import pack1.EmpTableModel;

public class EmpUI01 extends JFrame {

	private JPanel contentPane;
	private JTable table;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					EmpUI01 frame = new EmpUI01();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public EmpUI01() {
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 800, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(12, 10, 760, 316);
		contentPane.add(scrollPane);
		
		table = new JTable();
		/*
		table.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null, null, null, null, null, null, null},
			},
			new String[] {
				"empno", "ename", "job", "mgr", "hiredate", "sal", "comm", "deptno"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		*/
		
		table.setModel(new EmpTableModel());
		table.getColumnModel().getColumn(0).setResizable(false);
		table.getColumnModel().getColumn(1).setResizable(false);
		table.getColumnModel().getColumn(2).setResizable(false);
		table.getColumnModel().getColumn(3).setResizable(false);
		table.getColumnModel().getColumn(4).setResizable(false);
		table.getColumnModel().getColumn(5).setResizable(false);
		table.getColumnModel().getColumn(6).setResizable(false);
		table.getColumnModel().getColumn(7).setResizable(false);
		scrollPane.setViewportView(table);
	}

}
profile
개발자 꿈나무
post-custom-banner

0개의 댓글