이벤트
- 컴포넌트
- add***
- 이벤트처리 클래스
- 종류
- interface (Listener)
- class (Adapter) : 많이 사용
- 이벤트 처리용 메서드 있음
1. 그림을 그리면 자동적으로 코딩, import가 됨
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
public class JFrameEx04 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameEx04 frame = new JFrameEx04();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameEx04() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //윈도우창에 x표시를 누르면 프로그램 종료됨
setBounds(100, 100, 450, 300);
contentPane = new JPanel(); // 프레임안에 그릴수 있는 영역 설정
contentPane.setBackground(Color.PINK); //패널 배경색
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("변경 라벨"); //라벨을 자동적으로 생성
lblNewLabel.setForeground(Color.RED); //폰트 컬러
lblNewLabel.setFont(new Font("굴림", Font.ITALIC, 15)); //폰트 스타일
lblNewLabel.setVerticalAlignment(SwingConstants.TOP); //글씨 수직 정렬
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); //글씨 평행 정렬
lblNewLabel.setBounds(12, 10, 181, 41); //라벨 크기
contentPane.add(lblNewLabel); //라벨을 패널에 자동적으로 추가함
}
}
2
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.ImageIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JToggleButton;
public class JButtonEx01 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JButtonEx01 frame = new JButtonEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JButtonEx01() {
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("난 버튼");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("마우스 클릭");
}
});
btnNewButton.setBounds(12, 10, 97, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("<html><font color= 'red'>난버튼</font></html>"); //HTML태그를 달아줘도 됨
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("영역에 들어옴");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("나왔음");
}
});
btnNewButton_1.setBounds(12, 43, 97, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("");
btnNewButton_2.setIcon(new ImageIcon("C:\\java\\workspace\\Jframe\\src\\button.png"));
btnNewButton_2.setBounds(35, 82, 53, 39);
contentPane.add(btnNewButton_2);
JToggleButton tglbtnNewToggleButton = new JToggleButton("New toggle button");
tglbtnNewToggleButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(tglbtnNewToggleButton.isSelected()); //토글 버튼을 눌렀는지 안눌렀는지 상태값을 알수 있음 //불린값 나옴
}
});
tglbtnNewToggleButton.setSelected(true);
tglbtnNewToggleButton.setBounds(12, 139, 135, 23);
contentPane.add(tglbtnNewToggleButton);
}
}
event 만들기
토글버튼 선택상태 표시 (bool값)
버튼에 이미지 넣기
3
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPasswordField;
public class JTextFieldEx01 extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel lblNewLabel;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTextFieldEx01 frame = new JTextFieldEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTextFieldEx01() {
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);
textField = new JTextField();
textField.setText("난 텍스트 필드");
textField.setBounds(12, 10, 301, 21);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//lblNewLabel.setText(textField.getText()); //클릭을 하면 텍스트필드 내용을 가져와서 라벨에 채움
//lblNewLabel.setText(passwordField.getText());
lblNewLabel.setText(new String(passwordField.getPassword()));
}
});
btnNewButton.setBounds(325, 9, 97, 23);
contentPane.add(btnNewButton);
lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(12, 103, 410, 31);
contentPane.add(lblNewLabel);
passwordField = new JPasswordField();
passwordField.setEchoChar('★');
passwordField.setBounds(12, 41, 301, 21);
contentPane.add(passwordField);
}
}
패스워드 필드
로컬변수 또는 지역변수로 변환
버튼에 이벤트 코딩하여 password필드값을 label에 나타냄
4
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class JuminCheckEx02 extends JFrame {
private JPanel contentPane;
private JTextField textField1;
private JPasswordField textField2;
private JLabel result;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JuminCheckEx02 frame = new JuminCheckEx02();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JuminCheckEx02() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 479, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField1 = new JTextField();
textField1.setBounds(12, 10, 131, 21);
contentPane.add(textField1);
textField1.setColumns(10);
JLabel lblNewLabel = new JLabel("-");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(145, 13, 36, 15);
contentPane.add(lblNewLabel);
textField2 = new JPasswordField();
textField2.setBounds(188, 10, 143, 21);
contentPane.add(textField2);
JButton btnNewButton = new JButton("검사하기");
btnNewButton.addMouseListener(new MouseAdapter() { //버튼클릭시 주민번호 체크하는 로직이 실행됨
@Override
public void mouseClicked(MouseEvent e) {
String a = textField1.getText(); //텍스트필드 값을 받음
String b = new String(textField2.getPassword()); //암호필드 값을 받아 문자로 만듬
String strJumin = a+b; //문자열을 붙임
int[] bits = {2,3,4,5,6,7,8,9,2,3,4,5};
int sum = 0;
for(int i=0; i<bits.length; i++){
sum += Integer.parseInt(strJumin.substring(i,i+1))*bits[i];
}
int last = Integer.parseInt(strJumin.substring(12,13));
int resul = (11-sum%11)%10;
if(resul == last){
result.setText("정확한 주민번호입니다.");
}else{
result.setText("부정확한 주민번호입니다.");
}
}
});
btnNewButton.setBounds(345, 9, 97, 23);
contentPane.add(btnNewButton);
result = new JLabel("결과 : ");
result.setBounds(12, 48, 430, 15);
contentPane.add(result);
}
}
5
전체화면 패널에는 BorderLayout을 하면 화면이 5분할이 되고
하나에 하나씩 밖에 Widget이 들어가지 않는다.
이것을 회피하는 방법은 분할된 화면에 또다시 패널을 넣고
패널 안에 위젯을 채워넣는 것이다.
삽입한 패널역시 레이아웃을 정의 하는게 가능하다.
위의 패널에는 FlowLayout 값이 디폴트로 정의 되어있다
중간에 삽입한 패널에는 GridLayout을 썼다
6
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 javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
public class LayoutEx02 extends JFrame {
private JPanel contentPane;
//CardLayout 객체를 필드변수로 만들어서 서로다른 이벤트에 변수로 사용가능하게 함
private CardLayout cl_panel = new CardLayout(0,0);
private JPanel panel;
/**
* 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, 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) {
cl_panel.show(panel, "name_11191612266589"); //CardLayout객체의 메소드 호출
}
});
btnNewButton.setBounds(12, 21, 97, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
cl_panel.show(panel, "name_11202365337919"); //CardLayout객체의 메소드 호출2
}
});
btnNewButton_1.setBounds(12, 54, 97, 23);
contentPane.add(btnNewButton_1);
panel = new JPanel();
panel.setBounds(121, 21, 301, 231);
contentPane.add(panel);
panel.setLayout(cl_panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.RED);
panel.add(panel_1, "name_11191612266589");
JPanel panel_2 = new JPanel();
panel_2.setBackground(Color.BLUE);
panel.add(panel_2, "name_11202365337919");
}
}
패널에 CardLayout 적용
패널안에 두개의 패널을 삽입후 색상지정
상위 패널을 필드변수로 만듦
실행시 버튼클릭을하면 두개의 내부패널을 번갈아 보여줌
7
import java.awt.BorderLayout;
import java.awt.EventQueue;
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 EventEx01 extends JFrame implements MouseListener { //현재클래스에 Listener를 구현하는 방법
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);
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.setBounds(12, 24, 97, 23);
contentPane.add(btnNewButton);
btnNewButton.addMouseListener(this); //자신의 클래스를 매개번수로 받는다
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
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
}
}
8
import java.awt.BorderLayout;
import java.awt.EventQueue;
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.setBounds(12, 22, 97, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(12, 55, 97, 23);
contentPane.add(btnNewButton_1);
//익명내부클래스 사용 //버튼마다 호출을 해줘야함 //코드가 길어짐
//장점은 하나하나 별도로 실행값을 줌
btnNewButton.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("버튼클릭");
}
});
btnNewButton_1.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("버튼클릭2");
}
});
}
}
9
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.EventQueue;
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 EventEx03 extends JFrame {
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 btnNewButton = new JButton("버튼 1");
btnNewButton.setBounds(12, 22, 97, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("버튼 2");
btnNewButton_1.setBounds(12, 53, 97, 23);
contentPane.add(btnNewButton_1);
btnNewButton.addMouseListener(new UserEvent()); //버튼에 한줄만 추가해 주면됨
btnNewButton_1.addMouseListener(new UserEvent()); //버튼에 한줄만 추가해 주면됨
}
class UserEvent implements MouseListener{ //이벤트의 구현 객체 만듦
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
// e.getSource() 이벤트를 발생시킨 객체의 내용을 봄 //어느 객채에서 발생했는지 구분 가능
System.out.println("마우스 클릭 : "+ e.getSource());
JButton btn = (JButton)e.getSource();
System.out.println(btn.getText()); //클릭한 객체 text출력
System.out.println(e.getX() + " / "+ e.getY()); //버튼중에 어디 클릭했는지 좌표
System.out.println(e.getClickCount()); //클릭 숫자 셈
}
@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
}
}
}
10
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
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 btnNewButton = new JButton("New button");
btnNewButton.setBounds(12, 20, 97, 23);
contentPane.add(btnNewButton);
//어뎁터를 사용하면 모든 메소드를 구현할 필요없이 필요한 메소드만 오버라이드 하면됨
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("마우스 클릭");
}
});
}
}
11
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.ActionEvent;
public class EventEx05 extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventEx05 frame = new EventEx05();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public EventEx05() {
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);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { //Performed는 엔터를 누르는 이벤트
System.out.println("엔터 누름");
}
});
textField.setBounds(12, 10, 348, 21);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(12, 41, 348, 21);
contentPane.add(textField_1);
textField_1.setColumns(10);
this.addWindowListener(new WindowListener() { //윈도우창 이벤트 처리
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("windowOpened");
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("windowIconified");
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("windowDeiconified");
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("windowDeactivated");
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("windowClosing");
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("windowClosed");
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
System.out.println("windowActivated");
}
});
}
}
12
//데이터를 담을 형식 만듬
public class Zipcode {
private String seq; //담은 데이터의 이름(참조변수)으로 사용됨
private String code;
private String sido;
private String gugun;
private String dong;
private String ri;
private String bunji;
//constructor
public Zipcode(String seq, String code, String sido, String gugun, String dong, String ri, String bunji) {
this.seq = seq;
this.code = code;
this.sido = sido;
this.gugun = gugun;
this.dong = dong;
this.ri = ri;
this.bunji = bunji;
}
//getter
public String getSeq() { //이름을 통해서 데이터를 불러올 수 있음
return seq;
}
public String getCode() {
return code;
}
public String getSido() {
return sido;
}
public String getGugun() {
return gugun;
}
public String getDong() {
return dong;
}
public String getRi() {
return ri;
}
public String getBunji() {
return bunji;
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class UtilEx {
//검색결과를 바로 출력하는 메소드
/*public void searchZipcode(String strDong) throws IOException{
BufferedReader br = null;
br = new BufferedReader(new FileReader("C:/java/workspace/ZipSearch/src/zipcode_seoul_utf8.csv"));
String line = "";
while((line = br.readLine()) != null){
//System.out.println(line);
String[] address = line.split(",");
//System.out.println(address[3]);
if(address[3].startsWith(strDong)){
//System.out.println(address[3]);
String result = String.format("[%s] %s %s %s %s %s", address[0], address[1], address[2], address[3], address[4], address[5] );
System.out.println(result);
}
}
br.close();
*/
//검색결과를 ArrayList<Zipcode> 객체로 내보내는 메소드
public ArrayList<Zipcode> searchZipcodes(String strDong) throws IOException{
BufferedReader br = null;
ArrayList<Zipcode> datas = new ArrayList<>(); //미리 정의해둔 Zipcode 객체형식으로 데이터를 저장할 ArrayList 만든다
br = new BufferedReader(new FileReader("C:/java/workspace/ZipSearch/src/zipcode_seoul_utf8.csv")); //파일 읽음
String line = "";
while((line = br.readLine()) != null){
String[] address = line.split(","); //쉼표로 단어를 끊음
if(address[3].startsWith(strDong)){ //4번째 인덱스의 값을 매개변수 strDong과 비교해서 글짜 처음부분이 일치하는지 확인
//일치하면 Zipcode형식에 데이터 담음
Zipcode data = new Zipcode(address[6] ,address[0], address[1], address[2], address[3], address[4], address[5]);
datas.add(data); //datas에 data를 축적함
}
}
br.close(); //try catch로 처리하지 않기 때문에 bufferedReader를 바로 닫아줌
return datas; //datas를 리턴
}
}
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class ZipSearchEx03 {
public static void main(String[] args) {
UtilEx u = new UtilEx();
try{
ArrayList<Zipcode> datas = u.searchZipcodes("개포"); //"개포"로 시작하는 동 찾기
for(Zipcode data : datas){
System.out.printf("[%s] %s %s %s %s %s \n",data.getCode(),data.getSido(),data.getGugun(),data.getDong(),data.getRi(),data.getBunji());
}
} catch (FileNotFoundException e) {
System.out.println("[에러] 파일을 찾을 수 없습니다.");
} catch (IOException e) {
System.out.println("[에러] 파일을 읽을 수 없습니다.");
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//주소검색
public class ZipSearchEx {
public static void main(String[] args) {
// exit 무한입력 구문
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("입력 : ");
String data = br.readLine();
if(data.equals("exit")){
break;
}
System.out.println(">> "+data);
}
System.out.println("프로그램 종료");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) try { br.close();} catch(IOException e){ }
}
}
}
13. 위의 주소찾기와 같은 패키지 내에서 클래스가 들어있음
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
public class TextSearch extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextArea textArea;
private JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TextSearch frame = new TextSearch();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TextSearch() {
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);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strDong = textField.getText();
UtilEx u = new UtilEx();
String result = "";
try {
ArrayList<Zipcode> datas = u.searchZipcodes(strDong);
for(Zipcode data : datas){
result +=String.format("[%s] %s %s %s %s %s \n",data.getCode(),data.getSido(),data.getGugun(),data.getDong(),data.getRi(),data.getBunji());
}
} catch (IOException e1) {
e1.printStackTrace();
}
//textArea.setText(textField.getText()+"\n");
textArea.setText(result);
textField.setText("");
}
});
textField.setBounds(12, 10, 290, 21);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
}
});
btnNewButton.setBounds(325, 9, 97, 23);
contentPane.add(btnNewButton);
scrollPane = new JScrollPane();
scrollPane.setBounds(12, 42, 410, 210);
contentPane.add(scrollPane);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
14
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.TextArea;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TextAreaEx extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TextAreaEx frame = new TextAreaEx();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TextAreaEx() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 520, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.append(textField.getText()+"\n");
}
});
textField.setBounds(12, 10, 340, 21);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//textArea.setText(textField.getText()+"\n"); //setText 기존의 것을 지우고 입력
textArea.append(textField.getText()+"\n"); //append 이어서 입력
}
});
btnNewButton.setBounds(383, 9, 97, 23);
contentPane.add(btnNewButton);
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBounds(12, 41, 468, 195);
contentPane.add(textArea);
}
}
댓글 없음:
댓글 쓰기