일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- NIO
- deque
- 큐
- Java
- spring boot
- math
- dfs
- sql
- alter
- 스프링부트
- map
- List
- Union-find
- javascript
- Calendar
- set
- priority_queue
- 리소스모니터링
- date
- 힙덤프
- 스택
- CSS
- union_find
- string
- scanner
- GC로그수집
- BFS
- Properties
- html
- JPA
- Today
- Total
매일 조금씩
12/11 - GUI(4) : JDialog, JMenu, Layout, Event 본문
데이터가 있는 component / widget
1. UI class View
2. data class Model -> (D)TO -> DAO
JSpinner
JCombobox
JList / JTable - 출력
JTree
* 개발하면 클래스가 점점 많아지는 단계 ...
* 구구단, 우편번호
※ 응용문제
사원명을 입력하면 사원에 대한 정보가 테이블로 출력
사원에 대한 정보 : empno, ename, job, sal, comm, deptno, dname, loc
프로젝트명: SearchEmp
(1) SearchEmpUI
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.EmpTableModel;
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 java.sql.SQLException;
import javax.swing.JTable;
public class SearchEmpUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTable table;
private JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SearchEmpUI frame = new SearchEmpUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SearchEmpUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 568);
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);
JButton btn = new JButton("검색");
btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 초기화 작업
try {
if(table != null) {
String strEname = textField.getText();
if(strEname.length() < 2) {
JOptionPane.showMessageDialog(SearchEmpUI.this, "2자 이상 입력해주세요", "경고", JOptionPane.WARNING_MESSAGE);
}else {
table.setModel( new EmpTableModel(strEname));
}
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btn.setBounds(507, 37, 97, 23);
panel.add(btn);
scrollPane = new JScrollPane();
scrollPane.setBounds(12, 104, 606, 395);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
(2) EmpTableModel
package model1;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class EmpTableModel extends AbstractTableModel {
private ArrayList<EmpTO> values;
private String[] columnNames = {"사원번호", "사원이름", "직책", "급여", "호봉", "부서번호", "부서이름", "부서위치"};
//ArrayList<ArrayList> datas2 = new ArrayList<ArrayList>();
public EmpTableModel() {
}
public EmpTableModel(String strEname) throws ClassNotFoundException, SQLException{
EmpDAO dao = new EmpDAO();
values = dao.searchEname(strEname);
}
// 컬럼 이름 넣기
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public int getColumnCount() {
// 컬럼의 갯수 / 안에서 가져오기 어려워서 그냥 정해줌
return 8;
}
@Override
public int getRowCount() {
// 데이터의 갯수
return values.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
String result = "";
EmpTO to = values.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.getSal();
break;
case 4 :
result = to.getGrade();
break;
case 5 :
result = to.getDeptno();
break;
case 6 :
result = to.getDname();
break;
case 7 :
result = to.getLoc();
break;
default :
}
return result;
}
// editable
public boolean isCellEditable(int rowIndex, int columnIndex) {
boolean[] columnEditables = new boolean[] {
false, false, false, false, false, false, false, false
};
return columnEditables[columnIndex];
}
}
(3) EmpDAO
ArrayList<EmpTO> searchEname(String strEname)
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 EmpDAO {
private Connection conn = null;
// 생성자
// 데이터베이스 접속
public EmpDAO() throws ClassNotFoundException, SQLException{
String url = "jdbc:mysql://localhost:3307/sample";
String user = "root";
String password = "!123456";
Class.forName("org.mariadb.jdbc.Driver");
this.conn = DriverManager.getConnection(url, user, password);
// Connection conn = DriverManager.getConnection(url, user, password);
}
// SQL 구문별 메소드 - 동이름과 함께 호출되는 메서드는 그 결과값을 ArrayList<ZipcodeTO>로 리턴
public ArrayList<EmpTO> searchEname(String strEname) throws ClassNotFoundException, SQLException{
ArrayList<EmpTO> result = new ArrayList<EmpTO>();
String sql = "select empno, ename, job, sal, grade, deptno, dname, loc from emp e inner join dept d using(deptno) inner join salgrade s on e.sal between s.losal and s.hisal where (e.ename like ?)";
PreparedStatement pstmt = this.conn.prepareStatement(sql);
pstmt.setString(1, strEname + "%");
ResultSet 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 seq = rs.getString("seq");
ZipcodeTO to = new ZipcodeTO(zipcode, sido, gugun, dong, ri, bunji, seq);
*/
// setter 사용
EmpTO to = new EmpTO();
to.setEmpno(rs.getString("empno"));
to.setEname(rs.getString("ename"));
to.setJob(rs.getString("job"));
to.setSal(rs.getString("sal"));
to.setGrade(rs.getString("grade"));
to.setDeptno(rs.getString("deptno"));
to.setDname(rs.getString("dname"));
to.setLoc(rs.getString("loc"));
result.add(to);
}
return result;
}
}
(4) EmpTO
setter / getter
package model1;
public class EmpTO {
// DAO로 받아온 값들을 조작할 수 있게 선언
private String empno;
private String ename;
private String job;
private String sal;
private String grade;
private String deptno;
private String dname;
private String loc;
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 getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
// 생성자 - setter
/*
public ZipcodeTO(String zipcode, String sido, String gugun, String dong, String ri, String bunji, String seq){
this.zipcode = zipcode;
this.sido = sido;
this.gugun = gugun;
this.dong = dong;
this.ri = ri;
this.bunji = bunji;
this.seq = seq;
}
*/
}
1. JDialog
하나의 프레임에 다이얼로그가 여러개
1) 만드는 방법(부모창 / 자식창)
JDialog 창의 main메서드 안의 코드를 부모창인 JFrame에서 필요한 순간에 넣는다.
다음은 자식창인 JDialog 만드는 방법이다.
이렇게 클래스를 만들 때 JDialog를 extends 하도록 만든다.
그리고 JDialog의 main 메서드내의 코드를
다음과 같이 JFrame에서 필요한 순간에 넣는다.
(JDialog에서는 main 메서드를 주석처리한다.)
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
JDialogEx01 dialog = new JDialogEx01("초기 데이터");
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 랑 비교
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
System.out.println("1");
dialog.setModal(true);
System.out.println("2");
// 화면에의 제어를 자식창에 위임
dialog.setVisible(true);
// 부모창으로 변경 / 자식창 닫으면 부모창으로 변경됨
System.out.println("3");
}
});
그러면 다음과 같이 실행된다.
2) 부모창과 자식창이 데이터를 전달하는 방법
데이터 위치에 따라 조금씩 달라짐 (외부/ JFrame / JDialog)
JFrame(데이터) => JDialog(데이터)
* 생성자
JDialog => JFrame
* getter
1) 생성자 데이터 전달 - 초기 데이터
2) 특정한 시점 (getter)에 데이터 전달 - 변경 데이터
3) 자식 창 닫을 때 데이터 전달 - 완료 데이터
전체코드는 다음과 같다.
(1) JDialogMainEx01,java (부모)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JDialog;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class JDialogMainEx01 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JDialogMainEx01 frame = new JDialogMainEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JDialogMainEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 생성자로 데이터 전달
JDialogEx01 dialog = new JDialogEx01("초기 데이터");
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 랑 비교
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
System.out.println("1");
dialog.setModal(true);
System.out.println("2");
// 화면에의 제어를 자식창에 위임
// setter, getter로 데이터 전달
dialog.setShareData("변경 데이터");
dialog.printShareData();
// 여기에 정지된 상태가 들어간다.
dialog.setVisible(true);
// 그래서 여길 기점으로 아래 위 데이터가 다른게 들어간다.
// 부모창으로 변경 / 자식창 닫으면 부모창으로 변경됨
System.out.println("3");
System.out.println(dialog.getShareData());
}
});
btnNewButton.setBounds(14, 12, 105, 27);
contentPane.add(btnNewButton);
}
}
(2) JDialogEx01.java (자식)
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class JDialogEx01 extends JDialog {
private final JPanel contentPanel = new JPanel();
// 데이터
private String shareData;
// setter랑 getter로 데이터 전달
public void setShareData(String shareData) {
this.shareData = shareData;
}
public String getShareData() {
return shareData;
}
// setter, getter 데이터 부르는 메서드
public void printShareData() {
System.out.println(this.shareData);
}
/**
* Launch the application.
*/
// public static void main(String[] args) {
// try {
// JDialogEx01 dialog = new JDialogEx01();
// dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// dialog.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* Create the dialog.
*/
public JDialogEx01() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 창닫기
JDialogEx01.this.setShareData("완료된 데이터");
JDialogEx01.this.dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 창닫기
// this.dispose()하면 안됨 여기서 this는 MouseEvent이다.
JDialogEx01.this.dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
// 생성자로 데이터 전달
// 생성자 오버로딩 / JDialogEx01() 안에 써도됨
public JDialogEx01(String shareData) {
this();
this.shareData = shareData;
System.out.println("shareData : " + shareData);
}
}
실행결과는 다음과 같다.
아이디 중복 검사, 주소 찾기 등에 쓰인다.
※ 주의할 점
1. modal
2. dialog에서 main하지마라 (frame에서 해야함)
3. 닫을 때 dispose() 해라
4. 데이터를 dialog에서 private정의해라
3) ColorChooser
JDialogMainEx02.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class JDialogMainEx02 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JDialogMainEx02 frame = new JDialogMainEx02();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JDialogMainEx02() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Color color = JColorChooser.showDialog(JDialogMainEx02.this, "파레트", Color.GREEN);
// 컬러 선택 안하고 취소버튼 누르면 null나오니까
// 선택 됐을 때만
if(color != null) {
System.out.println(color.getRed());
System.out.println(color.getGreen());
System.out.println(color.getBlue());
}
System.out.println(color);
}
});
btnNewButton.setBounds(14, 12, 105, 27);
contentPane.add(btnNewButton);
}
}
4) FileChooser
open / save
open - 확장자를 지정할 수 있다.
확장자 지정으로 특정파일만을 걸러서 볼수 있다.
JDialogMainEx03.java
실습) Java File View
java파일중 하나를 가져와서 TextArea에 띄우고 그걸 다시 저장하기
JavaFileViewerEx01.java
파일 저장 마저 구현
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.UIManager;
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class JavaFileViewerEx01 extends JFrame {
private JPanel contentPane;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaFileViewerEx01 frame = new JavaFileViewerEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JavaFileViewerEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 553, 484);
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"), "\uC790\uBC14 \uD30C\uC77C \uBDF0\uC5B4", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
panel.setBounds(14, 12, 507, 60);
contentPane.add(panel);
panel.setLayout(null);
JButton btn1 = new JButton("자바 파일 열기");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btn1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
JFileChooser fileChooser = new JFileChooser("c:\\Java");
FileNameExtensionFilter filter = new FileNameExtensionFilter("Java Source File", "java");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(JavaFileViewerEx01.this);
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
//System.out.println(selectedFile.getName());
//System.out.println(selectedFile.getAbsolutePath());
//textArea.setText(selectedFile.getName());
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(selectedFile));
String line = null;
while((line = br.readLine()) != null){
textArea.append(line + "\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null) try { br.close();} catch(IOException e1) {}
}
}else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("취소");
}
}
});
btn1.setBounds(20, 20, 130, 27);
panel.add(btn1);
JButton btn2 = new JButton("자바 파일 저장");
btn2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JFileChooser fileChooser = new JFileChooser("c:\\Java");
int result = fileChooser.showSaveDialog(JavaFileViewerEx01.this);
// open일 때랑 같은 if문
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(selectedFile));
bw.write(textArea.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
if(bw != null)try { bw.close();} catch(IOException e1) {}
}
JOptionPane.showInternalMessageDialog(JavaFileViewerEx01.this, "파일 저장 성공","파일 저장", JOptionPane.INFORMATION_MESSAGE);
}else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("취소");
}
}
});
btn2.setBounds(164, 20, 130, 27);
panel.add(btn2);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(14, 78, 507, 347);
contentPane.add(scrollPane);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
2. JMenu
menubar > menu > menuItem
actionPerform 사용
Swing
1. Container
2. LayoutManager
Null (absolute)
* 기본 레이아웃
setLayout(레이아웃 클래스명)
JFrame / JDialog - BorderLayout
JPanel - FlowLayout
3. Widget
4. Event
Listener - 감시
Adapter
Event
* 발생시점
- Window - JFrame / JDialog - 열기 닫기 , 비활성화, 최소화
- Action - 마우스 클릭, 키보드 엔터, 아이템 선택
- Mouse - 클릭, 오버, 영역내(밖)
- Keyboard
3. Layout
모두 직접 코딩이 아닌 Design에서 그리는 형식이기 때문에 코드 업로드는 많이 하지 않는다.
1) BorderLayout
2) FlowLayout
LayoutEx01.java
panel넣고 안에 버튼 넣으면 버튼 크기에 따라서 panel사이즈 변함
밖은 boreder layout쓰고 안쪽은 absolute를 쓴다. 라고 보면 된다.
3) CardLayout
LayoutEx02.java
main패널을 만들고 그걸 card패널로 만든다.
그 안에 여러개의 패널을 만드는데 각각은 이름값을 가진다.
각각의 패널을 가져올 때 그 이름값을 가져온다.
각각의 패널들을 카드들이라고 보고 main패널을 카드들을 가지는 패널로 봐라.
버튼클릭하면 이름에 일치하는 카드 패널 가져오기
((CardLayout)panel.getLayout()).show(panel, "name_194003486855500");
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LayoutEx02 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LayoutEx02 frame = new LayoutEx02();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LayoutEx02() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 582, 468);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(14, 50, 317, 296);
contentPane.add(panel);
panel.setLayout(new CardLayout(0, 0));
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.CYAN);
panel.add(panel_1, "name_194003486855500");
panel_1.setLayout(null);
JButton btnNewButton_3 = new JButton("New button");
btnNewButton_3.setBounds(0, 37, 105, 27);
panel_1.add(btnNewButton_3);
JPanel panel_2 = new JPanel();
panel_2.setBackground(Color.ORANGE);
panel.add(panel_2, "name_194077745205300");
panel_2.setLayout(null);
JButton btnNewButton_4 = new JButton("New button");
btnNewButton_4.setBounds(109, 106, 105, 27);
panel_2.add(btnNewButton_4);
JPanel panel_3 = new JPanel();
panel_3.setBackground(Color.BLUE);
panel.add(panel_3, "name_194172173884200");
panel_3.setLayout(null);
JButton btnNewButton_5 = new JButton("New button");
btnNewButton_5.setBounds(198, 239, 105, 27);
panel_3.add(btnNewButton_5);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
((CardLayout)panel.getLayout()).show(panel, "name_194003486855500");
}
});
btnNewButton.setBounds(14, 22, 105, 27);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
((CardLayout)panel.getLayout()).show(panel, "name_194077745205300");
}
});
btnNewButton_1.setBounds(120, 22, 105, 27);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
((CardLayout)panel.getLayout()).show(panel, "name_194172173884200");
}
});
btnNewButton_2.setBounds(226, 22, 105, 27);
contentPane.add(btnNewButton_2);
}
}
4) GridLayout
LayoutEx03.java
4. Event
add이벤트종류Listener → 이벤트종류Listener(이너클래스) → 각 이벤트별 메서드
'이벤트종류Listener' 만 치고 ctrl + enter 하면 자동 완성됨
1) 이벤트 종류 : Window
EventEx01.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class EventEx01 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventEx01 frame = new EventEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public EventEx01() {
// 자동으로 닫기는 부분
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add이벤트종류Listener -> 이벤트종류Listener(이너클래스) -> 각 이벤트별 메서드
// 이벤트 종류 : Window
this.addWindowListener(new WindowListener() { // 이너클래스
// 각 이벤트별 메서드
@Override
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened(WindowEvent e)");
}
@Override
public void windowIconified(WindowEvent e) {
System.out.println("windowIconified(WindowEvent e)");
}
@Override
public void windowDeiconified(WindowEvent e) {
System.out.println("windowDeiconified(WindowEvent e)");
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("windowDeactivated(WindowEvent e)");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing(WindowEvent e)");
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("windowClosed(WindowEvent e)");
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("windowActivated(WindowEvent e)");
}
});
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
2) 이벤트 종류 : Mouse
버튼 마우스 클릭 이벤트 직접 주기
+ 이벤트종류Adapter => 필요한 이벤트 메서드만 써줌
EventEx02.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
public class EventEx02 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventEx02 frame = new EventEx02();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public EventEx02() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased(MouseEvent e)");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed(MouseEvent e)");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited(MouseEvent e)");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouseEntered(MouseEvent e)");
}
@Override
public void mouseClicked(MouseEvent e) {
// '클릭되었다'는 뜻으로 눌렀을때가 아니라 뗐을 때 나옴
System.out.println("mouseClicked(MouseEvent e)");
}
});
btnNewButton.setBounds(14, 12, 105, 27);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
// addMouseListener -> MouseListener(전체 구현) => 귀찮다
// 그래서 -> MouseAdapter(이미위에걸 다 구해놓은거라서) => 필요메서드만
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked(MouseEvent e)");
}
});
btnNewButton_1.setBounds(14, 51, 105, 27);
contentPane.add(btnNewButton_1);
}
}
버튼이 여러갠데 이벤트들을 같이 한번에 통합처리 하려면?
3) 이벤트 통합 처리 -> 인터페이스 클래스 사용
클래스에 implements MouseListener 해야한다.
그리고 메서드 추가는 아래처럼 한다.
그런다음 아래처럼 코드 추가하면 된다.
btn1.addMouseListener(this);
btn2.addMouseListener(this);
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.ActionEvent;
public class EventEx03 extends JFrame implements MouseListener{
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventEx03 frame = new EventEx03();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public EventEx03() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btn1 = new JButton("버튼 1");
btn1.setBounds(14, 12, 105, 27);
btn1.addMouseListener(this);
contentPane.add(btn1);
JButton btn2 = new JButton("버튼 2");
btn2.setBounds(14, 51, 105, 27);
btn2.addMouseListener(this);
contentPane.add(btn2);
}
// 마우스 이벤트 처리
@Override
public void mouseClicked(MouseEvent e) {
// 버튼1인지 버튼2인지 구별 불가
//System.out.println("마우스 클릭");
// 매우 많은게 출력됨
//System.out.println("마우스 클릭" + e);
// 위의 출력으로 알수 있는 값
// 버튼이 클릭된 좌표값
System.out.println(e.getX() + " / " + e.getY());
// 소스 - 버튼에 대한 정보 (여기 text에 버튼 이름이 들어감)
System.out.println(e.getSource());
// 소스에서 text 발췌하기
JButton btn = (JButton)e.getSource();
System.out.println(btn.getText());
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
4) 이벤트 통합 처리 -> 내부 인스턴스(스태틱) 클래스 사용
EventEx04.java
내부 인스턴스 클래스 사용
내부 스태틱 클래스 사용해도됨
class UserMouseEvent implements MouseListener
위와 같이 클래스내에 새로운 내부 인스턴스 클래스 UserMouseEvent 를 만들고
호출할땐 다음과 같이 호출하면 된다.
btn1.addMouseListener(new UserMouseEvent());
btn2.addMouseListener(new UserMouseEvent());
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.ActionEvent;
public class EventEx04 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventEx04 frame = new EventEx04();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public EventEx04() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btn1 = new JButton("버튼 1");
btn1.setBounds(14, 12, 105, 27);
btn1.addMouseListener(new UserMouseEvent());
contentPane.add(btn1);
JButton btn2 = new JButton("버튼 2");
btn2.setBounds(14, 51, 105, 27);
btn2.addMouseListener(new UserMouseEvent());
contentPane.add(btn2);
}
// 내부 인스턴스(스태틱) 클래스
class UserMouseEvent implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("마우스 클릭");
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}
여러 UI에서 클래스를 같이범용해서 쓴다면? 외부클래스화 해야한다.
※ 응용문제
콤보박스 세개만들어서 리스트로 주소 출력되게 하기 (강사님 풀이는 월요일에!)
1) 주소를 리스트로 출력하기
2) 주소를 테이블로 출력하기
3) 리스트로 출력 된 주소를 Dialog로 띄우고 받아와서 상세주소 입력받기
이렇게 세가지 방법으로 구현하였다.
우편번호 검색을 위한 주소 데이터만 있어서 그걸로 주소 검색을 하듯 구현하였다.
메인메서드가 있는 UI클래스는 다 다르지만,
그 외의 클래스는 최대한 공유하게 만들었다.
다음은 각각 사용하는 클래스이다.
1) 주소를 리스트로 출력하기
- ZipcodeSearchListUI
- ZipcodeComboModel
- ZipcodeListModel
- ZipcodeDAO
- ZipcodeTO
2) 주소를 테이블로 출력하기
- ZipcodeSearchTableUI
- ZipcodeComboModel
- ZipcodeTableModel
- ZipcodeDAO
- ZipcodeTO
3) 리스트로 출력 된 주소를 Dialog로 띄우고 받아와서 상세주소 입력받기
- ZipcodeSearchJFrameUI
- ZipcodeSearchJDialogUI
- ZipcodeComboModel
- ZipcodeListModel
- ZipcodeDAO
- ZipcodeTO
1, 2, 3 번 모두 같은 ZipcodeDAO, ZipcodeTO를 사용한다.
1, 2, 3 번 모두 콤보박스를 사용하므로 같은 ZipcodeComboModel 을 사용한다.
리스트를 사용하는 1, 3 번은 ZipcodeListModel 을 사용하고,
테이블을 사용하는 2 번은 ZipcodeTableModel 을 사용한다.
아래 코드에서 중복되는 클래스는 처음 한번만 업로드 하였다.
1) 리스트로 출력하기
(1) ZipcodeSearchListUI
import java.awt.BorderLayout;
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.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.border.TitledBorder;
import model1.ZipcodeComboModel;
import model1.ZipcodeDAO;
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 java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JComboBox;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ZipcodeSearchListUI extends JFrame {
private JPanel contentPane;
private JList list;
private JComboBox comboBox2;
private JComboBox comboBox3;
private JComboBox comboBox1;
private JScrollPane scrollPane;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JTextField textField1;
private JTextField textField2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZipcodeSearchListUI frame = new ZipcodeSearchListUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ZipcodeSearchListUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 565);
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, 66);
contentPane.add(panel);
panel.setLayout(null);
// comboBox, list 생성
// 이렇게 전부 위쪽에 생성 안해주면 나중에 NullPointerException 발생
comboBox1 = new JComboBox();
comboBox2 = new JComboBox();
comboBox3 = new JComboBox();
list = new JList();
// --------------------- comboBox1 ---------------------
try {
// 주소의 '시.도'들을 모두 comboBox1에 넣음
comboBox1.setModel(new ZipcodeComboModel());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
comboBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
try {
// comboBox1에서 '시.도'를 선택하면
// 선택된 '시.도'의 '구.군'을 comboBox2에 넣음
String strSido = (String)comboBox1.getSelectedItem();
comboBox2.setModel(new ZipcodeComboModel(strSido));
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
comboBox1.setBounds(38, 24, 150, 24);
comboBox1.addItem("시.도 선택");
panel.add(comboBox1);
// --------------------- comboBox2 ---------------------
comboBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
try {
// comboBox2에서 '구.군'을 선택하면
// 선택된 '시.도','구.군'의 '동'을 comboBox3에 넣음
String strSido = (String)comboBox1.getSelectedItem();
String strGugun = (String)comboBox2.getSelectedItem();
comboBox3.setModel(new ZipcodeComboModel(strSido, strGugun));
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
comboBox2.setBounds(235, 24, 150, 24);
comboBox2.addItem("구.군 선택");
panel.add(comboBox2);
// --------------------- comboBox3 ---------------------
comboBox3.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
try {
// comboBox3에서 '동'을 선택하면
// 선택된 '시.도', '구.군', '동'의 주소들을 list에 넣음
String strSido = (String)comboBox1.getSelectedItem();
String strGugun = (String)comboBox2.getSelectedItem();
String strDong = (String)comboBox3.getSelectedItem();
list.setModel(new ZipcodeListModel(strSido, strGugun, strDong));
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
comboBox3.setBounds(435, 24, 150, 24);
comboBox3.addItem("동 선택");
panel.add(comboBox3);
// --------------------- list (ScrollPane) ---------------------
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 99, 612, 310);
contentPane.add(scrollPane);
scrollPane.setViewportView(list);
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// list에서 주소 하나를 선택하면 그걸 textField1에 넣음
textField1.setText((String)list.getSelectedValue());
}
});
lblNewLabel = new JLabel("기본 주소");
lblNewLabel.setBounds(10, 433, 62, 18);
contentPane.add(lblNewLabel);
lblNewLabel_1 = new JLabel("상세 주소");
lblNewLabel_1.setBounds(10, 475, 62, 18);
contentPane.add(lblNewLabel_1);
textField1 = new JTextField();
textField1.setEditable(false);
textField1.setBounds(80, 430, 539, 24);
contentPane.add(textField1);
textField1.setColumns(10);
textField2 = new JTextField();
textField2.setBounds(80, 472, 539, 24);
contentPane.add(textField2);
textField2.setColumns(10);
}
}
(2) ZipcodeComboModel
package model1;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
public class ZipcodeComboModel extends DefaultComboBoxModel<Object>{
private ArrayList<String> values;
public ZipcodeComboModel() throws ClassNotFoundException, SQLException{
ZipcodeDAO dao = new ZipcodeDAO();
values = dao.searchZipcodeSido();
}
public ZipcodeComboModel(String strSido) throws ClassNotFoundException, SQLException{
ZipcodeDAO dao = new ZipcodeDAO();
values = dao.searchZipcodeGugun(strSido);
}
public ZipcodeComboModel(String strSido, String strGugugun) throws ClassNotFoundException, SQLException{
ZipcodeDAO dao = new ZipcodeDAO();
values = dao.searchZipcodeDong(strSido, strGugugun);
}
// callback - combobox 자동으로 불리워지는 메서드
@Override
public int getSize() {
return values.size();
}
@Override
public Object getElementAt(int index) {
return values.get(index);
}
}
(3) ZipcodeListModel
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<ZipcodeTO> values;
public ZipcodeListModel() {
}
public ZipcodeListModel(String strSido, String strGugun, String strDong) throws ClassNotFoundException, SQLException{
ZipcodeDAO dao = new ZipcodeDAO();
values = dao.searchZipcode(strSido, strGugun, strDong);
}
@Override
public String getElementAt(int index) {
ZipcodeTO value = values.get(index);
String address = String.format("[%s] %s %s %s %s %s\n", value.getZipcode(), value.getSido(), value.getGugun(),
value.getDong(), value.getRi(), value.getBunji());
return address;
}
@Override
public int getSize() {
return values.size();
}
}
(4) ZipcodeDAO
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() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3307/sample";
String user = "root";
String password = "!123456";
Class.forName("org.mariadb.jdbc.Driver");
this.conn = DriverManager.getConnection(url, user, password);
// Connection conn = DriverManager.getConnection(url, user, password);
}
// 시.도 가져오기
public ArrayList<String> searchZipcodeSido() throws ClassNotFoundException, SQLException {
ArrayList<String> result = new ArrayList<String>();
String sql = "select distinct sido from zipcode";
PreparedStatement pstmt = this.conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
String sido = "";
while (rs.next()) {
// setter 사용
sido = rs.getString("sido");
result.add(sido);
}
System.out.println("result : " + result);
return result;
}
// 시.도 입력 받은 것과 일치하는 구.군 을 가져오기
public ArrayList<String> searchZipcodeGugun(String strSido) throws ClassNotFoundException, SQLException {
ArrayList<String> result = new ArrayList<String>();
String sql = "select distinct gugun from zipcode where sido = ?";
PreparedStatement pstmt = this.conn.prepareStatement(sql);
pstmt.setString(1, strSido);
ResultSet rs = pstmt.executeQuery();
String gugun = "";
while (rs.next()) {
// setter 사용
gugun = rs.getString("gugun");
result.add(gugun);
}
System.out.println("result : " + result);
return result;
}
// 시.도 , 구.군 입력 받은 것과 일치하는 동을 가져오기
public ArrayList<String> searchZipcodeDong(String strSido, String strGugun)
throws ClassNotFoundException, SQLException {
ArrayList<String> result = new ArrayList<String>();
String sql = "select distinct dong from zipcode where sido = ? and gugun = ?";
PreparedStatement pstmt = this.conn.prepareStatement(sql);
pstmt.setString(1, strSido);
pstmt.setString(2, strGugun);
ResultSet rs = pstmt.executeQuery();
String dong = "";
while (rs.next()) {
// setter 사용
dong = rs.getString("dong");
result.add(dong);
}
System.out.println("result : " + result);
return result;
}
// 시.도 , 구.군 , 동 입력받은 것과 일치하는 주소들을 가져오기
public ArrayList<ZipcodeTO> searchZipcode(String strSido, String strGugun, String strDong)
throws ClassNotFoundException, SQLException {
ArrayList<ZipcodeTO> result = new ArrayList<ZipcodeTO>();
String sql = "select * from zipcode where sido = ? and gugun = ? and dong = ?";
PreparedStatement pstmt = this.conn.prepareStatement(sql);
pstmt.setString(1, strSido);
pstmt.setString(2, strGugun);
pstmt.setString(3, strDong);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// setter 사용
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"));
result.add(to);
}
System.out.println("result : " + result);
return result;
}
}
(5) ZipcodeTO
package model1;
public class ZipcodeTO {
// DAO로 받아온 값들을 조작할 수 있게 선언
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String ri;
private String bunji;
private String seq;
// setter
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;
}
// getter
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;
}
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
}
2) 테이블로 출력하기
(1) ZipcodeSearchTableUI
import java.awt.BorderLayout;
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.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.border.TitledBorder;
import model1.ZipcodeComboModel;
import model1.ZipcodeDAO;
import model1.ZipcodeListModel;
import model1.ZipcodeTableModel;
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 java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JComboBox;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
public class ZipcodeSearchTableUI extends JFrame {
private JPanel contentPane;
private JComboBox comboBox2;
private JComboBox comboBox3;
private JComboBox comboBox1;
private JLabel lbl1;
private JLabel lbl2;
private JTextField textField1;
private JTextField textField2;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZipcodeSearchTableUI frame = new ZipcodeSearchTableUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ZipcodeSearchTableUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 565);
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, 66);
contentPane.add(panel);
panel.setLayout(null);
// comboBox, table 생성
// 이렇게 전부 위쪽에 생성 안해주면 나중에 NullPointerException 발생
comboBox1 = new JComboBox();
comboBox2 = new JComboBox();
comboBox3 = new JComboBox();
table = new JTable();
// --------------------- comboBox1 ---------------------
try {
comboBox1.setModel(new ZipcodeComboModel());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
comboBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
try {
String strSido = (String)comboBox1.getSelectedItem();
comboBox2.setModel(new ZipcodeComboModel(strSido));
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
comboBox1.setBounds(38, 24, 150, 24);
comboBox1.addItem("시.도 선택");
panel.add(comboBox1);
// --------------------- comboBox2 ---------------------
comboBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
try {
String strSido = (String)comboBox1.getSelectedItem();
String strGugun = (String)comboBox2.getSelectedItem();
comboBox3.setModel(new ZipcodeComboModel(strSido, strGugun));
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
comboBox2.setBounds(236, 24, 150, 24);
comboBox2.addItem("구.군 선택");
panel.add(comboBox2);
// --------------------- comboBox3 ---------------------
comboBox3.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
try {
if(table != null) {
String strSido = (String)comboBox1.getSelectedItem();
String strGugun = (String)comboBox2.getSelectedItem();
String strDong = (String)comboBox3.getSelectedItem();
table.setModel( new ZipcodeTableModel(strSido, strGugun, strDong));
}
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
comboBox3.setBounds(435, 24, 150, 24);
comboBox3.addItem("동 선택");
panel.add(comboBox3);
// --------------------- table ---------------------
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(table.getSelectedRow());
int row = table.getSelectedRow();
String address = "";
System.out.println(table.getValueAt(row, 0));
address = String.format("[%s] %s %s %s %s %s",
table.getValueAt(row, 0),table.getValueAt(row, 1),table.getValueAt(row, 2),
table.getValueAt(row, 3),table.getValueAt(row, 4),table.getValueAt(row, 5));
textField1.setText(address);
}
});
lbl1 = new JLabel("기본 주소");
lbl1.setBounds(10, 433, 62, 18);
contentPane.add(lbl1);
lbl2 = new JLabel("상세 주소");
lbl2.setBounds(10, 475, 62, 18);
contentPane.add(lbl2);
textField1 = new JTextField();
textField1.setEditable(false);
textField1.setBounds(80, 430, 539, 24);
contentPane.add(textField1);
textField1.setColumns(10);
textField2 = new JTextField();
textField2.setBounds(80, 472, 539, 24);
contentPane.add(textField2);
textField2.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 99, 610, 312);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
}
}
(2) ZipcodeComboModel
위와 동일
(3) ZipcodeTableModel
package model1;
import java.io.ObjectInputStream.GetField;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class ZipcodeTableModel extends AbstractTableModel {
private ArrayList<ZipcodeTO> values;
private String[] columnNames = {"우편번호", "시도", "구군", "동", "리", "번지"};
public ZipcodeTableModel() {
}
public ZipcodeTableModel(String strSido, String strGugun, String strDong) throws ClassNotFoundException, SQLException{
ZipcodeDAO dao = new ZipcodeDAO();
values = dao.searchZipcode(strSido, strGugun, strDong);
}
// 컬럼 이름 넣기
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public int getColumnCount() {
// 컬럼의 갯수 / 안에서 가져오기 어려워서 그냥 정해줌
return 6;
}
@Override
public int getRowCount() {
// 데이터의 갯수
return values.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
String result = "";
ZipcodeTO to = values.get(rowIndex);
switch(columnIndex) {
case 0 :
result = to.getZipcode();
break;
case 1 :
result = to.getSido();
break;
case 2 :
result = to.getGugun();
break;
case 3 :
result = to.getDong();
break;
case 4 :
result = to.getRi();
break;
case 5 :
result = to.getBunji();
break;
default :
}
return result;
}
// editable
public boolean isCellEditable(int rowIndex, int columnIndex) {
boolean[] columnEditables = new boolean[] {
false, false, false, false, false, false
};
return columnEditables[columnIndex];
}
}
(4) ZipcodeDAO
위와 동일
(5) ZipcodeTO
위와 동일
3) 리스트로 출력 된 것을 Dialog로 띄우고 받아와서 상세주소 입력받기
(1) ZipcodeSearchJFrameUI
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ZipcodeSearchJFrameUI extends JFrame {
// main 메서드로 인해 객체가 생성되고 실행되는데 그과정에서
// 멤버변수나 메서드가 쓰이려면 (외부클래스에서 불리워지는것도 포함)
// main이 static이므로 staic이야한다.
// 외부클래스에서 불리워지는 것도
// 어쨋든 main 메서드 실행 중에일어나는 것이므로 같은 경우이다.
private JPanel contentPane;
private static JTextField textField1;
private static JTextField textField2;
private JTextField textField3;
public static void setTextField(String address) {
textField1.setText(address.substring(1,8));
textField2.setText(address.substring(10));
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZipcodeSearchJFrameUI frame = new ZipcodeSearchJFrameUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ZipcodeSearchJFrameUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 496, 334);
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"), "\uC8FC\uC18C \uC785\uB825", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
panel.setBounds(28, 26, 421, 136);
contentPane.add(panel);
panel.setLayout(null);
textField1 = new JTextField();
textField1.setEditable(false);
textField1.setBounds(18, 25, 116, 24);
panel.add(textField1);
textField1.setColumns(10);
JButton btn1 = new JButton("우편번호 검색");
btn1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
try {
// 우편번호 검색창 dialog 띄움
ZipcodeSearchJDialogUI dialog = new ZipcodeSearchJDialogUI();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn1.setBounds(147, 24, 121, 27);
panel.add(btn1);
textField2 = new JTextField();
textField2.setEditable(false);
textField2.setBounds(18, 61, 389, 24);
panel.add(textField2);
textField2.setColumns(10);
textField3 = new JTextField();
textField3.setBounds(94, 97, 313, 24);
panel.add(textField3);
textField3.setColumns(10);
JLabel lblNewLabel = new JLabel("상세 주소");
lblNewLabel.setBounds(18, 100, 68, 18);
panel.add(lblNewLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(28, 213, 421, 47);
contentPane.add(scrollPane);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
JButton btn2 = new JButton("등록");
btn2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String str = String.format("[%s] %s, %s",
textField1.getText(), textField2.getText(), textField3.getText());
textArea.setText(str);
}
});
btn2.setBounds(201, 174, 76, 27);
contentPane.add(btn2);
}
}
(2) ZipcodeSearchJDialogUI
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.TitledBorder;
import model1.ZipcodeComboModel;
import model1.ZipcodeListModel;
import javax.swing.UIManager;
import java.awt.Color;
public class ZipcodeSearchJDialogUI extends JDialog {
private final JPanel contentPanel = new JPanel();
private JComboBox comboBox1;
private JComboBox comboBox2;
private JComboBox comboBox3;
private JScrollPane scrollPane;
private JList list;
// JFrame에 전달할 주소 데이터
private String address;
// setter랑 getter로 데이터 전달
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
/**
* Launch the application.
*/
// public static void main(String[] args) {
// try {
// ZipcodeSearchJDialogUI dialog = new ZipcodeSearchJDialogUI();
// dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// dialog.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* Create the dialog.
*/
public ZipcodeSearchJDialogUI() {
setBounds(100, 100, 639, 519);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.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(24, 12, 573, 73);
contentPanel.add(panel);
panel.setLayout(null);
// comboBox, list 생성
// 이렇게 전부 위쪽에 생성 안해주면 나중에 NullPointerException 발생
comboBox1 = new JComboBox();
comboBox2 = new JComboBox();
comboBox3 = new JComboBox();
list = new JList();
// -------------------- comboBox1 --------------------
try {
comboBox1.setModel(new ZipcodeComboModel());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
comboBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
String strSido = (String) comboBox1.getSelectedItem();
comboBox2.setModel(new ZipcodeComboModel(strSido));
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
comboBox1.setBounds(38, 24, 135, 24);
comboBox1.addItem("시.도 선택");
panel.add(comboBox1);
// -------------------- comboBox2 --------------------
comboBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
String strSido = (String) comboBox1.getSelectedItem();
String strGugun = (String) comboBox2.getSelectedItem();
comboBox3.setModel(new ZipcodeComboModel(strSido, strGugun));
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
comboBox2.setBounds(220, 24, 135, 24);
comboBox2.addItem("구.군 선택");
panel.add(comboBox2);
// -------------------- comboBox3 --------------------
comboBox3.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
String strSido = (String) comboBox1.getSelectedItem();
String strGugun = (String) comboBox2.getSelectedItem();
String strDong = (String) comboBox3.getSelectedItem();
list.setModel(new ZipcodeListModel(strSido, strGugun, strDong));
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
comboBox3.setBounds(400, 24, 135, 24);
comboBox3.addItem("동 선택");
panel.add(comboBox3);
// -------------------- list (ScrollPane) --------------------
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(24, 99, 573, 310);
contentPanel.add(scrollPane);
scrollPane.setViewportView(list);
// -------------------- Dialog 버튼 --------------------
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(list.getSelectedValue() != null) {
// ok버튼 누르면 list에서 선택된 주소를 부모창 textField에 넣음
ZipcodeSearchJDialogUI.this.setAddress((String)list.getSelectedValue());
ZipcodeSearchJDialogUI.this.dispose();
ZipcodeSearchJFrameUI.setTextField(address);
}else {
// list에서 주소를 선택하지 않으면 경고창 띄움
JOptionPane.showMessageDialog(ZipcodeSearchJDialogUI.this, "주소를 선택해주세요", "경고", JOptionPane.WARNING_MESSAGE);
}
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
ZipcodeSearchJDialogUI.this.dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
}
(3) ZipcodeComboModel
위와 동일
(4) ZipcodeListModel
위와 동일
(5) ZipcodeDAO
위와 동일
(6) ZipcodeTO
위와 동일
'빅데이터 플랫폼 구축을 위한 자바 개발자 양성과정' 카테고리의 다른 글
12/18 - JSP(1) : 이클립스 + 톰캣 설정, 작성, 실행 방법 (0) | 2020.12.22 |
---|---|
12/14 - Java로 메일 발송 (텍스트, html, 이미지, 첨부파일) (0) | 2020.12.15 |
12/10 - GUI(3) : JSpinner, JComboBox, JList, JTable, JTree (0) | 2020.12.10 |
12/09 - GUI(2) : JCheckBox, JRadioButton, JOptionPane, JProgreeBar, JSlider (0) | 2020.12.10 |
12/08 - GUI(1) : Swing, Window Builder (JLabel, JButton, JTextField, JTextArea) (0) | 2020.12.10 |